Home > Mobile >  React.js with fetch api and console.log()
React.js with fetch api and console.log()

Time:08-07

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?

CodePudding user response:

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>

CodePudding user response:

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>
    )
}

CodePudding user response:

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>
    )
}
  • Related