I have this project for a perfume store.
I have this CARD component of a perfume.
Basically I would like the user to click on the card and render a new component with full details of card. So, for that I pass via path an id parameter.
{
state.map(c => (
<Grid item xs={4} sm={2} >
<PerfumeCard key={c.id} perfume={c} />
<button className="myButton2"> <NavLink
style={{ textDecoration: "none" }}
to={{
pathname: '/home/myperfume/' + c.id,
}}>
Click here for details
</NavLink></button>
</Grid>
))
}
so far I have no issues.
on my CARD DETAILS component I use useParams() in order to fetch the id so I can save in the state the perfume since I am using a Redux store.
const params = useParams()
const id = params.id;
const [state, setState] = useState<any>('');
and fetching the object:
setState(store.getState().perfumeState.perfumes[id]);
Now when I check my console for debugging I see that when I use console.log it shows the correct ID, however, when I console.log the actual state saved while passing the ID I get a different object with a different ID.
lets say I click on card with id 1.
Console.log(id) = 1;
console.log(state) =
MyPerfume.tsx:29 {id: 2, name: 'Green Irish Tweed', type: 'EDT', gender: 'UNISEX', season: 'SUMMER', …}
as you can see I get returned the object of id 2 for some reason
and when I press card with ID 2 I get returned the object with ID 5 for example.
what causes this Behavior? I could not seem to get my hands on the problem, however, I know I am missing somthing.
is there a better way in which I could fetch the object without this issue?
Still new to this.
Thanks!
store.getState().perfumeState.perfumes[id] doesn't mean it will send the perfume with id=1, it will send the perfume in the position 1 of the perfumes array, that's why is different on the server, try to use a array.find
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find