Reputation: 1202
I have following code inside my functional component.
const { id } = useParams();
const categories = useSelector((state) => {
const allCategories = state.allCategories;
return allCategories.filter(cat => cat.id === id);
});
const [code, setCode] = useState(categories.length === 1 ? categories[0].code : '');
However this code runs correctly only once. Then if I refresh the page, it doesn't work. Please help me to fix this issue. Also, if this is against best practices, please let me know the correct way to do this. Actual use case is, there is a category table and user clicks on "edit category" and then I navigate to this component to display the current data (ie: category code). Since, the category table already has data, allCategories is filled
Upvotes: 1
Views: 1962
Reputation: 5745
because the data is changed in some other place of the program its prolematic to use it as a default state value...
instead bind the value with useEffect()
const { id } = useParams();
const categories = useSelector((state) => {
const allCategories = state.allCategories;
return allCategories.filter(cat => cat.id === id);
});
const [code, setCode] = useState('');
useEffect(()=>{
if(categories.length === 1)
setCode(categories[0].code)
},[categories.length&&categories[0].?code])
NOTE: the code will be set like so whenever categories[0].code
is changed...
Upvotes: 1
Reputation: 84
You can use something like redux-persist to save the redux state to local storage or to another storage system
Upvotes: 0