skip to Main Content

Promice is rewriting value of hook, i tried to get more values to my posts, but promise keep replacing value of hook with value of data

const loadNewProducts = async() =>{
            while(posts.length<15){
            await fetch (`http{loadLimit[0]}&limit=${loadLimit[1]}&sort=title%3Aasc`)           
            .then((res) => res.json())
            .then((data) => {
                data.data.map((data: { id: any; }) => {if (posts.includes((post: { id: any; }) => post.id!=data.id)||posts.length==0) {setPosts(posts => [...posts, data])}});
                setPosts(posts => posts.slice(-data.data.length));console.log(posts);
                
            })
            .catch((err) => {
                console.log(err.message);
            });
            loadLimit = [loadLimit[0],loadLimit[1]+1];if(loadLimit[1]==13){loadLimit = [loadLimit[0]+1,1]}}}



        // eslint-disable-next-line react-hooks/exhaustive-deps
        useEffect(() => {{loadNewProducts();console.log(posts);loadNewProducts();console.log(posts)}}, [])

I trie a lot of ways to solve this, but nothing helped

2

Answers


  1. try using useRef like below –

    import { useEffect, useState, useRef } from "react";
    
    const loadNewProducts = async (loadLimit, postsRef, setPosts) => {
      while (postsRef.current.length < 15) {
        try {
          const res = await fetch(`http{loadLimit[0]}&limit=${loadLimit[1]}&sort=title%3Aasc`);
          const data = await res.json();
          const newPosts = data.data.filter((item) => !postsRef.current.some((post) => post.id === item.id));
          if (newPosts.length > 0) {
            setPosts((prevPosts) => {
              const updatedPosts = [...prevPosts, ...newPosts];
              postsRef.current = updatedPosts;
              return updatedPosts;
            });
          }
    
          loadLimit = [loadLimit[0], loadLimit[1] + 1];
          if (loadLimit[1] === 13) {
            loadLimit = [loadLimit[0] + 1, 1];
          }
        } catch (err) {
          console.log(err.message);
        }
      }
    };
    
    const YourComponent = () => {
      const [posts, setPosts] = useState([]);
      const postsRef = useRef(posts);
    
      useEffect(() => {
        const loadLimit = [0, 1];
        loadNewProducts(loadLimit, postsRef, setPosts);
      }, []);
    
      return (
        <div>
          {posts.map((post, index) => (
            <div key={index}>{post.title}</div>
          ))}
        </div>
      );
    };
    
    export default YourComponent;
    

    let me know if it worked. change YourComponent to whatever your component is

    Login or Signup to reply.
  2. const loadNewProducts = async () => {
      while (posts.length < 15) {
        try {
          const res = await fetch(`http{loadLimit[0]}&limit=${loadLimit[1]}&sort=title%3Aasc`);
          const data = await res.json();
    
          setPosts((prevPosts) => {
            const newPosts = data.data.filter((item) => !prevPosts.some((post) => post.id === item.id));
            return [...prevPosts, ...newPosts];
          });
    
          setLoadLimit((prevLimit) => {
            const [page, limit] = prevLimit;
            return limit === 13 ? [page + 1, 1] : [page, limit + 1];
          });
        } catch (err) {
          console.error(err.message);
        }
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search