I am having a redux state in which i want to store data, which iam getting from an api, to display specific data on different pages. Here is my reducer code:
const INIT_STATE = {
movies: []
};
export const moviereducer = (state = INIT_STATE, action) => {
switch (action.type) {
case "ADD_MOVIE":
return {
movies: [action.payload]
}
default:
return state
}
}
I am having this hero component from which I am calling api and mapping the data, component code:
const Hero = () => {
const [data, setData] = useState([])
const Dispatch = useDispatch();
const fetchData = () => {
return axios.get("https://api.tvmaze.com/search/shows?q=all")
.then((response) => setData(response.data));
}
useEffect(() => {
fetchData()
}, [])
console.log(data)
const handleClick = (ele => {
Dispatch(ADD(ele))
})
return (
<div className='heroWrap'>
<div className='cardWrap'>
{
data && data.map((ele, id) => {
return (
<Card key={id} style={{ width: '18rem' }}>
<Card.Img variant="top" />
<Card.Body>
<Card.Title>{ele.show.name}</Card.Title>
<Card.Text>
Genres: {ele.show.genres + ','}
</Card.Text>
<Button onClick={handleClick(ele)} variant="primary">
<Link className='text-white' to='/detail'>Read More</Link>
</Button>
</Card.Body>
</Card>
)
})
}
</div>
</div>
)
}
No matter on which renderd item button I click on, it only save the same data in my redux state
Here is the data iam getting from api:
And here is what the state it saving:
2
Answers
create anonymous function and call
handleClick
inside that.Within your reducer you have to return the state which will be the state that is stored. In your case with your
ADD_MOVIE
action you return the state withmovies
as a property with the value of an array that contains one item which is the payload that is given to the action (by doing[action.payload]
. I think what you want to do is navigate on click to a page that has theid
or some other identifier in the url which you can get from the url and then using a selector select the specific movie you want with something likeif you are not using react router of course you can try to save the selected id in the store or something.