Not able to implement data from one api used to get data from another

Viewed 18

I am making a meme sharing app. In that app there are total 2 apis of getting memes. One for memes by all the users another is only for individual user. In second api I am able to get the data as the user id is from 3rd api. from here i get the id of each individual.

function UserProfile({memeid}) {
const token = localStorage.getItem("token");

const [response, setResponse] = useState({});
const [id, setId] = useState('')
const userData = async() => {
  await axios
    .get("http://localhost:8081/userInfo/me", {
      headers: { Authorization: `Bearer ${token}` },
      Accept: "application/json",
      "Content-Type": "application/json",
     })
    .then((res) => {
      setResponse(res.data)
      setId(res.data.id)
      memeid = id
    })
    .catch((err)=>{
      console.log(err)
    })

}
console.log(id)
useEffect(()=>{
  userData()
},[])

Now I want this to be used in in another api. for that is have written this code.

function MemeById({id}) {

const [response, setResponse] = useState([])
const token = localStorage.getItem("token");

// const id = "632a119672ba0e4324b18c7d"

const memes = async () => {
  await axios
    .get("http://localhost:8081/memes/" + id, {
      headers: { Authorization: `Bearer ${token}` },
      Accept: "application/json",
      "Content-Type": "application/json",
    })
    .then((res) => {
      const data = res.data;
      setResponse(res.data)
      console.log(data);
    })
     .catch((err) => {
      alert(err);
      console.log(err);
    });
};

useEffect(()=>{
  memes()
},[])

I am calling these two at User

function User() {

let id;


return (
  <div>
    <UserProfile memeid={id}/>
    <MemeById id = {id}  />
  </div>
)

}

I am getting the error for this. How to solve this error

1 Answers

You're making a big mistake. I think you should learn more about state and props in react.

Problem :

In your User component, you're creating a variable and passing that variable into two other component. You're trying to update the value of props from UserProfile and expecting that updated value in MemeById which is not going to work.

Solution :

function User() {
    const [memeId, setMemeId] = useState(null);

    return (
    <div>
        <UserProfile updateId={(newId) => setMemeId(newId)}/>
        <MemeById memeId = {memeId}  />
    </div>
    )
}

And in your UserProfile component

function UserProfile({updateId}) {
...
const userData = async() => {
    ...
    // memeid = id
    updateId(res.data.id)
    ...
}

In you MemeById component:

function MemeById({memeId}) {
    ...
    // use memeId here
    ...
}
Related