I am trying to update the Child
component if the reducer function in Parent
component runs successfully.
function reducer(state, action) {
if (action.type === "something") {
try {
action.cb();
return { ...state, updated: true };
} catch (error) {
action.cb(error)
}
}
}
function Parent() {
const [state, dispatch] = useReducer(reducer)
return <Child dispatch={dispatch}></Child>
}
function Child({ dispatch }) {
const [state, setState] = useState(false)
function handleClick () {
function cb(err) {
if (!err) {
setState(true)
}
}
dispatch({ type: "something", cb: cb });
}
return <button onClick={handleClick}>Click me</button>;
}
But when I run the above code I get a warning
Warning: Cannot update a component (Child) while rendering a different component (Parent)
how can I update the Child
component’s state if there is no error in the reducer
function?