How To Dispatch In Useeffect?
I tried to set a state using useState inside useEffect with no problem, code as follows: Now I'd like to do the same thing but with useReducer, I tried to modify the above code to
Solution 1:
You're setting the reducer with the same state property as it was before in this case you're basically doing:
title: state.title
And since your default state is a title with an empty array value you're not changing anything.
You need to use the action argument in your reducer to accomplish what you want:
const bannerReducer = (state, action) => {
switch(action.type) {
case'setTitle':
return {
...state,
title: action.title
}
}
}
And your dispatch should be something like this:
dispatch({type: 'setTitle', title: response.title});
Solution 2:
Your useReducer
call is not inside the function, therefore doesn't get attached to it.
Call it like this:
constBanner = () => {
const [title, setTitle] = useState([]);
const [state, dispatch] = useReducer(bannerReducer, {title: []});
useEffect(() => {
asyncfunctionfetchData() {
const api = 'some api url';
let response = awaitfetch(api);
response = await response.json();
dispatch({type: 'setTitle', response.title});
}
fetchData();
}, []);
}
Also keep in mind that your useEffect
runs every time the Banner
function gets called. Consider adding a dependencies array as stated here in the hooks tutorial: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
Post a Comment for "How To Dispatch In Useeffect?"