shan
shan

Reputation: 1202

How to use useSelector on page refresh

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

enter image description here

enter image description here

Upvotes: 1

Views: 1962

Answers (2)

adir abargil
adir abargil

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

Anil Kumar
Anil Kumar

Reputation: 84

You can use something like redux-persist to save the redux state to local storage or to another storage system

Upvotes: 0

Related Questions