-1

Hi guys i'm trying to loop through this array that im getting from this array: "https://us-central1-nft-cloud-functions.cloudfunctions.net/hotCollections"

I have a function that gives me the nftId as params, I want to use those params to target the same id that the one of the object of the array has and I want to display the information that matches.

the Code:

  const {nftId} = useParams();
  const [posts, setPost] = useState([]);

 console.log(nftId)
  

  async function fetchPost(nftId) {
    const {data} = await axios.get(`https://us-central1-nft-cloud-functions.cloudfunctions.net/hotCollections`)
    setPost(data)
    let lookup = {};
    
    for (let i = 0; i < posts.length; i++) {
      if (posts.nftId === nftId) {
        lookup[posts[i].nftId] = posts[i]
        console.log(lookup)
      }
    }

    //data.filter(x => x.nftId === nftId).map(x=> console.log(x))

  }
  useEffect(() => {
    fetchPost()
  }, [])
  
  • tldr, use `data` instead of `posts` – Konrad Apr 16 '23 at 18:27
  • What is your issue? Do you get an error? Nothing is diaplayed? The code responsible for what is rendered is missing. – yjay Apr 16 '23 at 22:08
  • is not a issue itself i want to know how can i loop through out the array to match the params that Im getting with the object that i want to target – Rudis Gomez Apr 16 '23 at 22:42
  • (A) React state updates are asynchronously processed, so `posts` is still the initial state in `fetchPost` and (B) route path params are ***always*** String types, so using strict equality with a Number type field value will never be equal. – Drew Reese Apr 17 '23 at 23:37

1 Answers1

0

The API is returning an array of objects. From your comments I think you want to find the object with nftId same than your params. As others suggested, you can simplify code to this.

const { nftId } = useParams();

async function fetchPost() {
  const { data } = await axios.get(`https://us-central1-nft-cloud-functions.cloudfunctions.net/hotCollections`)
  
  for (let i = 0; i < data.length; i++) {
    const obj = data[i];
    const nftIdFromApi = obj.nftId;

    if (nftIdFromApi === nftId) {
      console.log(obj);
    }
  }
}

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