1

I can't log or display data in this barebones React component. I am trying to just simply fetch my repos using the fetch api. I am getting a response back when I look at Network tab in dev tools.

I tried to wrap the call in useEffect() (then storing the data from the response into a state variable) - that didn't work so that's why I have this barebones component for now.

const Component = () => {
    const [repos, setRepos] = useState([])
    
    useEffect(() => {
        // fetch call used to be here
    }, [])

    const data = fetch('https://api.github.com/users/alexspurlock25/repos')
                     .then(response => response.json())
                     .then(data => setRepos(data))

    console.log(data)
    console.log(repos)

    return (
        <div>
        {
            repos.map(items => console.log(items))
        }
        </div>
    )
}

Why can't I log or map the data? Am I doing something wrong?

1
  • 1
    put it back inside the useEffect. Also, don't assign the fetch call to a variable. Normally it's easier to use the async await syntax Commented Aug 6, 2022 at 23:57

3 Answers 3

1

Create an async function that handles the api call. Then call the function in the useEffect. Since Repos is an empty array, nothing will be logged. Once your api call resolves and the repos state has been updated, react will do it's thing and re render causing the repos.map to run again and log out the repos

const Component = () => {
    const [repos, setRepos] = useState([])
    
    const fetchData = async ()=>{
    
    let res = await fetch('https://api.github.com/users/alexspurlock25/repos')
    let data = await res.json()
    setRepos(data)
    
    }
    
    
    useEffect(() => {
        // fetch call used to be here
        fetchData()
    }, [])


    return (
        <div>
        {
            repos.map(items => console.log(items))
        }
        </div>
    )
}
Sign up to request clarification or add additional context in comments.

3 Comments

If I try to log repos anywhere, nothing is logged. If I log data, I get a result in the log. It's like setRepos() is not doing its job. What do you think? So far, I think, your solution is on to something.
Nevermind, I use your code as solution. async, await is what did it. Thank you!
setState is asynchronous . So even if you were to call console.log() right after setting your state, the log will fire before the values are updated
0

You have to verify that the repos are defined and contain data to do that you can do the following

//mock up API
const API = (ms = 800) => new Promise(resolve => setTimeout(resolve, ms, {state:200, data:[1,2,3,5]}));

ReactDOM.render(
    <App />,
    document.body
);



function App(props){
  const [repos, setRepos] = React.useState([]);
  
  React.useEffect(() => {
    API()
    .then(res => setRepos(res.data));
  },[])
  
  
  return <div>{
     // Check Here
    repos.length > 1 ? repos.map((r,i) => <div key={`${r}-${i}`}>{r}</div>) : <div>Loading ...</div>
  }</div>
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

Comments

0
const Component = () => {
    const [repos, setRepos] = useState([])
    
    useEffect(() => {
    const data = fetch('https://api.github.com/users/alexspurlock25/repos')
                     .then(response => response.json())
                     .then(data => setRepos(data))

    console.log(data)
    }, [])

    
    console.log(repos)

    return (
        <div>
        {
            repos.map(items => console.log(items))
        }
        </div>
    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.