Nika Roffy
Nika Roffy

Reputation: 941

pass paramater to useEffect()

I want to get id of the current rendered item(in my case topic).I'm trying to do it via useEffect() hook but it seems it can not accept paramaters. Is there any way to fix it and pass recieved data to other elements?

Here is the full functional component of mine :

    const PostOnPage: React.FunctionComponent = () => {
  // Dont let in without token
  useEffect(() => {
    axios
      .get(`http://localhost:4000/`, {
        headers: {
          "auth-token": localStorage.getItem("auth-token"),
        },
      })
      .then((res) => {
        console.log("--------res.data", res.data);
      })
      .catch((err) => {
        console.log("err", err);
        toast.info("You must Log In");
        history.push("/login");
      });
  }, []);

  //Get Post By Id
 useEffect((id : Number) => {
     axios
         .get(`http://localhost:4000/getTopic/${id}`)
         .then((post) => {
           console.log('--------post.data', post.data.description);
         })
         .catch((err)=>{
           console.log('--------err', err);
         })
 })

  const LogOut = () => {
    localStorage.clear();
    history.push("/login");
  };

  const history = useHistory();
  let posts: any = useSelector((state: any) => state.posts);

  return (
    <div id="card" className="card">
      <div id="postButtons" className="buttons">
        <button onClick={() => history.push("/homepage")}>Home</button>
        <button onClick={() => history.push("/profile")}>My Profile</button>
        <button onClick={() => LogOut()}>Log Out</button>
      </div>
      <div className="posts">
        <p>
          Title :
          {posts.map((title: any) => {
            return title.title;
          })}
        </p>

        <p>
          Description :
          {posts.map((item : any) => {return getPostById(item.id)})}
        </p>
      </div>
    </div>
  );
};

export default PostOnPage;

Upvotes: 1

Views: 17793

Answers (3)

mfe
mfe

Reputation: 1208

if you store Id in state then you can trigger useEffect if id is change. in below example I stored id in state and us it to in second useEffect function. you also need to add change parameter of useEffect

 const PostOnPage: React.FunctionComponent = () => {
  const [id,setId]=useState()
  // Dont let in without token
  useEffect(() => {
    axios
      .get(`http://localhost:4000/`, {
        headers: {
          "auth-token": localStorage.getItem("auth-token"),
        },
      })
      .then((res) => {
        setId(res.data.id)
        console.log("--------res.data", res.data);
      })
      .catch((err) => {
        console.log("err", err);
        toast.info("You must Log In");
        history.push("/login");
      });
  }, []);

  //Get Post By Id
 useEffect(() => {
     axios
         .get(`http://localhost:4000/getTopic/${id}`)
         .then((post) => {
           console.log('--------post.data', post.data.description);
         })
         .catch((err)=>{
           console.log('--------err', err);
         })
 },[id])

  const LogOut = () => {
    localStorage.clear();
    history.push("/login");
  };

  const history = useHistory();
  let posts: any = useSelector((state: any) => state.posts);

  return (
    <div id="card" className="card">
      <div id="postButtons" className="buttons">
        <button onClick={() => history.push("/homepage")}>Home</button>
        <button onClick={() => history.push("/profile")}>My Profile</button>
        <button onClick={() => LogOut()}>Log Out</button>
      </div>
      <div className="posts">
        <p>
          Title :
          {posts.map((title: any) => {
            return title.title;
          })}
        </p>

        <p>
          Description :
          {posts.map((item : any) => {return getPostById(item.id)})}
        </p>
      </div>
    </div>
  );
};

export default PostOnPage;

Upvotes: 1

AvivBS
AvivBS

Reputation: 76

useEffect hook is used to execute functionality according to data change / onload. It can't receive parameters, If you want to use the id of your current render in your useEffect you should send him as prop.

Upvotes: 4

Durgesh Pal
Durgesh Pal

Reputation: 695

useEffect hook doesn't take a parameter. You have to pass the parameter in the component.

const Component = ({ id }) => {

    useEffect(() => {
        axios
            .get(`http://localhost:4000/getTopic/${id}`)
            .then((post) => {
                console.log('--------post.data', post.data.description);
            })
            .catch((err) => {
                console.log('--------err', err);
            })
    })

    return (
         // your render
          )
}

Upvotes: 1

Related Questions