'I can render my page just once. After refreshing the page, i am getting an error as cant find data from api. Please let me know my mistake

I use useEffect to call api to fetch data. Data contains 10 arrays sets. In section = container, i fetched required data to specific section (layout done through css) . i can fetch data only once, after refreshing, error showing "cant found data". Please let me know my mistake

function App() {
    
      const [posts, setPosts] = useState([])
      const url = 'https://api.tvmaze.com/search/shows?q=all';
    
      useEffect(() => {
        fetch(url).then(resp => resp.json())    //api call
          .then(resp => setPosts(resp))
      }, []);
    
    
      return (
        <div class="App">
          
          <header class="App-header">
            <h1>WELCOME TO ZENERSPACE CINEMAS!!</h1>
          </header>
        
          {console.log(posts)}
         
          <div class="container-fluid">
            <section id="container">
    
              <div>
                <img src={myImg1} alt="" />   // fetching data from api call
                <a href={posts[0].show.url}>{`${posts[0].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto"><Link to="/Home">Show more details</Link></button>
              </div>
              <div>
                <img src={myImg2} alt="" />
                <a href={posts[1].show.url}>{`${posts[1].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
              <div>
                <img src={myImg3} alt="" />
                <a href={posts[2].show.url}>{`${posts[2].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto"
                > Show more details
                </button>
              </div>
              <div>
                <img src={myImg4} alt="" />
                <a href={posts[3].show.url}>{`${posts[3].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
              <div>
                <img src={myImg5} alt="" />
                <a href={posts[4].show.url}>{`${posts[4].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
              <div>
                <img src={myImg6} alt="" />
                <a href={posts[5].show.url}>{`${posts[5].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
              <div>
                <img src={myImg7} alt="" />
                <a href={posts[6].show.url}>{`${posts[6].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
              <div>
                <img src={myImg8} alt="" />
                <a href={posts[7].show.url}>{`${posts[7].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
              <div>
                <img src={myImg9} alt="" />
                <a href={posts[8].show.url}>{`${posts[8].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
              <div>
                <img src={myImg10} alt="" />
                <a href={posts[9].show.url}>{`${posts[9].show.name}`} </a>
                <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
            </section>
    
          </div>
    
          <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossOrigin="anonymous"></script>
          <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossOrigin="anonymous"></script>
    
        </div>
    
      );
    }
    
    export default App;


Solution 1:[1]

Here you go:

Some stuff: .map( ) function would definitely be better to use instead of array index to access items one-by-one plus less code and clean code.

import React, { useEffect, useState } from "react"

function App() {

  const [posts, setPosts] = useState([])

  useEffect(() => {
    const fetchData = () => {
      fetch("https://api.tvmaze.com/search/shows?q=all")
        .then(res => res.json())
        .then(json => {
          setPosts(json)
        })
    }
    fetchData()
  }, []);


  return (
    <div className="App">

      <header className="App-header">
        <h1>WELCOME TO ZENERSPACE CINEMAS!!</h1>
      </header>

      <div className="container-fluid">
        <section id="container">
          {
            posts.map(ele => (
              <div key={ele.show.id}>
                <a href={ele.show.url}>{`${ele.show.name}`}</a>
                <button type="button" className="btn btn-danger btn-md mx-auto">Show more details</button>
              </div>
            ))
          }
        </section>

      </div>
    </div>

  );
}

export default App;

Screenshot-Page: Screenshot-Output

Screenshot-NetworkScreenshot-Output

Solution 2:[2]

If you're getting errors while you refresh the page this may help you: every time you make an API request it takes some time to retrieve data and when your app tries to access posts state which is still empty react flow error which say that you're are trying to access data that is undefined, to solve it allow your app to access posts while is not an empty array.

{posts.length>0&& <section id="container">.....</section>}

With your code:

function App() {

  const [posts, setPosts] = useState([])
  const url = 'https://api.tvmaze.com/search/shows?q=all';

  useEffect(() => {
    fetch(url).then(resp => resp.json())    //api call
      .then(resp => setPosts(resp))
  }, []);


  return (
    <div class="App">
      
      <header class="App-header">
        <h1>WELCOME TO ZENERSPACE CINEMAS!!</h1>
      </header>
     
      <div class="container-fluid">
        {posts.length>0&&
        <section id="container">

          <div>
            <img src={myImg1} alt="" />   // fetching data from api call
            <a href={posts[0].show.url}>{`${posts[0].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto"><Link to="/Home">Show more details</Link></button>
          </div>
          <div>
            <img src={myImg2} alt="" />
            <a href={posts[1].show.url}>{`${posts[1].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
          <div>
            <img src={myImg3} alt="" />
            <a href={posts[2].show.url}>{`${posts[2].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto"
            > Show more details
            </button>
          </div>
          <div>
            <img src={myImg4} alt="" />
            <a href={posts[3].show.url}>{`${posts[3].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
          <div>
            <img src={myImg5} alt="" />
            <a href={posts[4].show.url}>{`${posts[4].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
          <div>
            <img src={myImg6} alt="" />
            <a href={posts[5].show.url}>{`${posts[5].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
          <div>
            <img src={myImg7} alt="" />
            <a href={posts[6].show.url}>{`${posts[6].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
          <div>
            <img src={myImg8} alt="" />
            <a href={posts[7].show.url}>{`${posts[7].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
          <div>
            <img src={myImg9} alt="" />
            <a href={posts[8].show.url}>{`${posts[8].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
          <div>
            <img src={myImg10} alt="" />
            <a href={posts[9].show.url}>{`${posts[9].show.name}`} </a>
            <button type="button" class="btn btn-danger btn-md mx-auto">Show more details</button>
          </div>
        </section>
        }
      </div>

      <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossOrigin="anonymous"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossOrigin="anonymous"></script>

    </div>

  );
}

export default App;

If you're want to console log posts data inside jsx also remember to log it after condition which evaluates the existence of data

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 RWUBAKWANAYO