skip to Main Content

Currently I’m learning react, and I’m the part of using fetch api, I was able fetch the data and display data on my local computer, but when in preview on my mobile which is connected to the same network is just showing data that were not fetched, what should I do inorder to view the fetched data?

I tried to add the port of the fetched url in my network firewall inbound rules, but still the fetched data is not showing.
Below is my code for my fetch api:

useEffect(() => {
        fetch('http://localhost:8000/destinations')
        .then(res => {
        if(!res.ok){        //error throwing
            throw Error('could not fetch the data for that resource');
          }
          return  res.json();
        })
        .then(data => {
           console.log(data);
        })
        .catch(err => {
            
            console.log(err.message);
        })
    }, []);

2

Answers


  1. Chosen as BEST ANSWER

    Already solved, I put my json inside public folder, and called in fetch as local file

    useEffect(() => {
    fetch('data.json')
        .then()
    })
    

  2. On Windows, you can open Command Prompt and type ipconfig. Look for the IPv4 Address under your active network connection.
    On Mac or Linux, use Terminal and type ifconfig or ip addr show and look for the IPv4 address.

    Replace localhost with your IP address in the fetch request:

    useEffect(() => {
    fetch('http://YOUR_COMPUTER_IP:8000/destinations')
        .then(res => {
            if (!res.ok) {
                throw Error('could not fetch the data for that resource');
            }
            return res.json();
        })
        .then(data => {
            console.log(data);
            // Update state or do something with the fetched data here
        })
        .catch(err => {
            console.log(err.message);
        })
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search