Я создал один пользовательский хук для вызова Api.Я пытаюсь установить одно значение флага, чтобы быть ложным, всякий раз, когда происходит вызов API.Как только я получу ответ, флаг должен измениться на false.Я отправил действие внутри вызова API, но не смог обновить значение состояния.
import { useEffect, useReducer } from "react";
import fetch from "axios";
const useApiHook = (url, reducer) => {
const [state, dispatch] = useReducer(reducer, { loading: false });
useEffect(() => {
fetch(url)
.then(dispatch({ type: "fetching", loading: true }))
.then(res => res.data)
.then(data => dispatch({ type: "success", loading: false, data }))
.catch(err => dispatch({ type: "fail", loading: false, err }));
}, [url]);
return state;
};
}
const Reducer = (state, action) => {
const { url, data, err } = action;
const currentState = state[url];
console.log("action", action);
console.log("state", state.loading);
switch (action.type) {
case "fetching":
return {
...state,
[url]: { ...currentState, loading: action.loading }
};
case "success":
return {
...state,
[url]: { ...currentState, loading: action.loading, data }
};
case "fail":
return {
...state,
[url]: { ...currentState, loading: action.loading, err }
};
default:
return state;
}
};
const Comp = () => {
const url = "https://randomuser.me/api/";
const sample = useApiHook(url, Reducer);
}
Может ли кто-нибудь помочь мне в обновлении состояния?