React Native useState doesn't update state

From my Api I am getting array of Objects like this:

[{
"category_param": {"id": 2, "name": "sport"}, 
"id": 2, "isSelect": false, "name": "temperature"
}, 
.........
{
"category_param": {"id": 1, "name": "food"}, 
"id": 99, "isSelect": false, "name": "location"
}]

After I get this data from Api, I am store it using useState. In data to work with it, and dataInit to save clean unfiltered data from Api:

const [data, setData] = useState([]);
const [dataInit, setDataInit] = useState([]); 

and on my screen I am outputs this data, and everything works well.
But,
I have on my screen filter buttons, that should filter my list by category_param.id:

     <TouchableOpacity
        key={0}
        accessibilityRole="button"
        onPress={() => onPress('')}
        >
        <Text>
          All
        </Text>
      </TouchableOpacity>
      <TouchableOpacity
        key={2}
        accessibilityRole="button"
        onPress={() => onPress(2)}
        >
        <Text>
          Sport
        </Text>
      </TouchableOpacity>
      <TouchableOpacity
        key={1}
        accessibilityRole="button"
        onPress={() => onPress(1)}
        >
        <Text>
          Food
        </Text>
      </TouchableOpacity>

And my onPress function is:

const onPress = id => {
    setData(dataInit); //Line #1
    if (id === '') {
      setData(dataInit); //Line #2
      return;
    }

    console.log('BEFORE TAB FILTER:::', data); //Line #3
    let filtered = data(item => {
      return item.category_param.id === id;
    });
    setData(filtered);//Line #4
    console.log('filtered:::', filtered);//Line #5
  };

So, the problem is when I press on Sport button (id=2) or Food button (id=1) exactly after my screen opens, it filters and on my screen data is filtered. When I after that click on All button (id=”), I see dataInit (//Line #2) – my all clean data from Api.

But when I click after my screen opens on Sport button (id=2), and then on Food button (id=1), result is empty, because as I see from console log //Line #3 – after first click on button, here is my initData, but after second click console log on //Line #3 not returns data, it returns my filtered data, that was set on //Line #4 after first click.

Is there any way to make setData(dataInit); //Line #1 works and put in data clean list form Api every time I click on any filter button?

>Solution :

I think it could be because of by clicking on Sport button you set your data to filtered data (as on let filtered = data(item => { return item.category_param.id === id; });), so, on next clicking to Food button you trying to filter already filtered data. setData in your case doesn’t set your data to default instantly.

If you have already saved init data, so, maybe you should just filter it, instead of setting data to default and trying to filter it (useless code as I think). If you have questions, you could write me 🙂

Leave a Reply