Ryan
Ryan

Reputation: 101

useEffect() not receiving prop

I'm semi-new to React and learning.

I implemented a useEffect() hook as follows:

import { fetchDetails } from "../../ApiServices/Details";

export interface RemoveModalProps {
    id: number;
    isVisible: boolean;
    onHide: () => void;
    handleRemove: (resp: JsonResponseModel<ApiResponse>) => void;
}

const RemoveModal= ({ id, isVisible, onHide, handleRemove }: RemoveModalProps) => {
const [details, setDetails] = React.useState<DetailsModel>();

React.useEffect(() => {
    console.log(id);
    async function getDetails() {
        var details= await fetchDetails(id);
        console.log(details.Data);
        setDetails(details.Data);
    }
    getDetails();
}, []); 

However, for reasons I'm not quite able to understand, the console.log(id) is returning null. However, I have the following function just below the useEffect()

const handleSubmit = async () => {
    const isValid = formRef.current.checkValidity();
    setValidated(true);
    if (isValid) {
        console.log(id);
        setSaving(true);
        const resp = await removeDetails(id);
    }
};

and THIS console.log(id) is logging the correct id, so obviously the id is being properly passed as a prop. What am I doing wrong with my useEffect hook that it's not able to use the prop?

Upvotes: 1

Views: 1068

Answers (1)

vamshi krishna
vamshi krishna

Reputation: 2927

useEffect accepts array of dependencies as second parameter. changes in values for dependencies will trigger function in side useeffect again and again.

In your case you need id as dependant value in useEffect. So

useEffect needs to look like this

React.useEffect(() => {
    console.log(id);
    async function getDetails() {
        var details= await fetchDetails(id);
        console.log(details.Data);
        setDetails(details.Data);
    }
    getDetails();
}, [id]); 

You may need to handle null/undefined value in id. I suggest you to do something like this.

React.useEffect(() => {
    if (!id) {
      return 
    }
    ... rest of hook
}, [id]); 

I suggest you to use eslint to warn about useEffect missing dependencies.

References :

useEffect documenation

Upvotes: 2

Related Questions