skip to Main Content

Actually, Iam working with next js 13.5+, after deployment in Versel, the fresh data is not being called, I saw other questions that are asked by others in Stack overflow, they’re using fetch method and not axios method in next js. Iam using axios method like this:

 const [data, setData] = useState<any>();
  useEffect(() => {
    axios.get("/api/admin/getAllCategories").then((res) => setData(res.data));
  }, []);

please tell me the solution of this, the data not being updated using useEffect and axios library.

I cannot switch to fetch method because i used this axios method in almost every file im my directory. any solutions with this axios method and not fetch method?

2

Answers


  1. You can do it like this with fetch.

    in home.js

    const sleep = (ms) => {
          return new Promise((resolve) => setTimeout(resolve, ms))
        }    
        const fetchData = async () => {
              const res = await fetch('http://localhost:adress/api/admin/getAllCategories')
              return res.json()
            }
        const Home = async () => {
          await sleep(3000)
          const data= await fetchData()
          console.log(data)
          return (
            <div>
              
            </div>
          )
        }
        export default Home
    

    If you are not doing it as a ‘use client’ and you are using the nextjs app router, you cannot use useeffect and use state. Please let me know if this approach solves your problem

    Login or Signup to reply.
  2. const getCategories = async () => {
        const response = await axios.get(http://localhost:adress/api/admin/getAllCategories');
            return response;
    };
    const Home = async () => {
          const data = (await getCetegories()
                .then(response => {
                    return response
                })
                .catch(error => {
                }))
    
          console.log(data)
    
          return (
            <div>
              
            </div>
          )
        }
        export default Home
    

    I haven’t tested it but this should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search