Home > front end >  React native - Need to change the state value to pass values to api call on each button click
React native - Need to change the state value to pass values to api call on each button click

Time:07-28

In my app there is a list(FLatList) with pagination.

There are two buttons for sorting the list

Button 1 -> to remove the sorting key and load the default data from api.

Button 2 -> Each click on this button need to pass the value 'a to z' and 'z to a' to api as params

How to change the state(setSort,setSortAsc) of the value on each click and call api function?

My try -

  const [getSort, setSort] = useState(false);
  const [getSortAsc, setSortAsc] = useState(false);

Button 1 -> onPress () =>

const onCustomSort = () => {
    setSort(false);
    checkSorting();
  };

Button 2 -> onPress () =>

  const onNameSort = () => {
    setSort(true);
    setSortAsc(!getSortAsc);
    checkSorting();
  };

const checkSorting = () => {
    console.log(TAG, 'Mrbee'   getSort   '---'   getSortAsc);

    setviewProduct([]);

    setLoader(true);
    
    if (getSort) {
      if (getSortAsc === true) {
        setSortType('a to z');
      } else {
        setSortType('z to a');
      }
    } else {
      setSortType('');
    }

    //api_call
     dispatch(productlistAction(...,...,getSortType,),);
  };

Issue is -> the state not getting change on button click so the api returns the same response. On multiple clicks the state getting changed.

Calling of setState is not working for any states! setviewProduct([]); setLoader(true);

What is the mistake here. P

CodePudding user response:

 const [getSort, setSort] = useState(false);
  const [getSortAsc, setSortAsc] = useState(false);
const [extra, setExtra] = useState(0);

Button 1 -> onPress () =>

  const onCustomSort = () => {
    setSort(false);
    setExtra(extra 1) //add this
    setTimeout(() => {
    checkSorting();
    }, "500")// 500 mean 0.5 sec delay, you can add your custom time
    
  };

Button 2 -> onPress () =>

  const onNameSort = () => {
    setSort(true);
    setSortAsc(!getSortAsc);
    setExtra(extra 1) //add this
    setTimeout(() => {
    checkSorting();
    }, "500") // 500 mean 0.5 sec delay, you can add your custom time
  };

const checkSorting = () => {
    console.log(TAG, 'Mrbee'   getSort   '---'   getSortAsc);

    setviewProduct([]);

    setLoader(true);
    
    if (getSort) {
      if (getSortAsc === true) {
        setSortType('a to z')
        setExtra(extra 1) //add this
      } else {
        setSortType('z to a');
        setExtra(extra 1) //add this
      }
    } else {
      setSortType('');
      setExtra(extra 1) //add this
    }

    //api_call
     dispatch(productlistAction(...,...,getSortType,),);
  };
  • Related