Home > Net >  get data by id then storing it on a state
get data by id then storing it on a state

Time:10-08

i was trying to get a row of data by id from existing array inside a state, is this the right way to do it? cause it keeps on doing the thing on loop, i was trying to do a similar thing but calling it from the api, but it had similar error where i got 429 http error, means i keep calling the api nonstop.

I was trying to get a row and then view the details on another component.

My function:

const getAnime = (id) => {
    let filteredAnime = data.filter((item) => item.mal_id === id) //data is a state
    console.log(filteredAnime)
    setAnime(filteredAnime) //this is setting a state
  };

The button:

<Button title="Detail" onPress={getAnime(item.mal_id)} />

The error:

[Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.] PayloadTooLargeError: request entity too large

I haven't thought of how to view details component, was thinking of using modal navigator, a suggestion beside the answer might be nice, i'm still new to react native.

Edit: Found a better way to pass the value without the need to use state, i don't know if it's actually better, but if it works, don't touch it I'm just passing the renderItem from flatlist as param from this method, and then calling them on the expected component. https://reactnavigation.org/docs/params/

CodePudding user response:

Try and change the way you are passing your function to the onPress. Talking from a ReactJs perspective, it's supposed to be:

<Button title="Detail" onClick={() => getAnime(item.mal_id)} />

but I guess you can change the onClick to onPress to suit your use case. Most important thing is to wrap the function in a callback to avoid multiple calls. I hope it works for you.

CodePudding user response:

you have to give callback to the function

<Button title="Detail" onPress={()=>getAnime(item.mal_id)} />

CodePudding user response:

Change the way you are calling the function in the button

<Button title="Detail" onPress={()=>getAnime(item.mal_id)} />

That will make the work :)

  • Related