1

I need to make api call when ComponentWillUnmount. Iam using state variable to set api request. when i access the state variable from ComponentWillUnmount. the state value is default one but am expecting recently updated state.


    export const sampleComponent: React.FC<IProps> = (props: IProps) => {
    const [apiValue, setAipValue] = useState("");
    const [updateRec] = useMutation(UPDATE_REC);
    ....
    setApiValue
    ....
    
    useEffect(()=>{
    return () => {callApi(apiValue)}
    }, []);
    }
    
    const callApi = (input) => {
    updateRec({
    variables : {
    data : input
    }
    });
    }

1 Answers1

1

Since your useEffect has empty dependencies ([]), the apiValue that is binded is only the inital value of apiValue

A solution would be to use a ref to track value

const apiValueRef = useRef();

apiValueRef.current = apiValue;

useEffect(() => {
  return () => {
    callApi(apiValueRef.current);
  }
}, []);
shantr
  • 724
  • 1
  • 6