Search code examples
javascriptreactjsreact-nativeaxiosuse-effect

change variable value with axios, useeffect, and usestate


i'm newbie here, i'm stuck. i want to change value from false to true, to stop shimmering when data sucessfully to load.

i have action like this

import axios from "axios";
import { CONSTANT_LINK } from "./constants";
import { GET } from "./constants";
import { ERROR } from "./constants";
import { connect } from 'react-redux';

export const addData = () => {
  return (dispatch) => {
    axios
      .get(CONSTANT_LINK)
      .then((res) => {
        dispatch(addDataSuccess(res.data));
      })
      .catch((err) => {
        dispatch(errorData(true));
        console.log("error");
      });
  };
};

const addDataSuccess = (todo) => ({
  type: GET,
  payload: todo,
});

const errorData = (error) => ({
  type: ERROR,
  payload: error,
});

and this is my homepage which influential in this matter

const [shimmerValue, setShimmerValue] = useState(false)
useEffect(() => { 
    setShimmerValue(true)
    dispatch(addData());
  }, []);
 <ShimmerPlaceholder visible={shimmerValue} height={20}>
            <Text style={styles.welcomeName}>Welcome,Barret</Text>
          </ShimmerPlaceholder>

i dont understand how it works


Solution

  • You can pass callback like this

    const [shimmerValue, setShimmerValue] = useState(false);
    
    const updateShimmerValue = () => {
      setShimmerValue(true);
    }
    useEffect(() => { 
        // setShimmerValue(true) // remove this from here
        dispatch(addData(updateShimmerValue)); // pass callback as param here
      }, []);
    

    Callback call here like

    export const addData = (callback) => {
      return (dispatch) => {
        axios
          .get(CONSTANT_LINK)
          .then((res) => {
            ....
            callback(); // trigger callback like this here
          })
          .catch((err) => {
            ....
          });
      };
    };