I'm trying to do some work using the useReducer
hook and react-router-dom
. I have 2 pages; 1) Home 2) Details. Using the react-router-dom
to navigate between 2 components. The details are added to the details page. In the submit action of the Details
page the despatch()
is called to save the state.
// In Details.js component
const [details, setDetails] = useState({
name: '',
age: ''
});
const save_book = (e) => {
e.preventDefault();
const modified_details = {...details, id: uuidv4()};
dispatch({ type: 'SAVE', payload: modified_details});
}
The reducer.js
file
export const default_state = {
details: []
}
// Reducer
export const reducer = (state, action) => {
if(action.type === 'SAVE'){
const modified_details = [...state.details, action.payload];
console.log(state);
return {...state, details: modified_details};
}
throw new Error ('HANDLED_ERROR: matching action type found!');
}
The details are saved in state
successfully. But when I try to navigate to the Home
component the state
is set to initial.
//In Home.js component
const Home = () => {
const [state, dispatch] = useReducer(reducer, default_state);
// This is a new state variable???
// This is empty.
// {
// "details": []
// }
return(<> <pre>{JSON.stringify(state, undefined, 2)}</pre> </>);
}
What I'm doing wrong?