Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Handling response status in React useEffect hook - lifecycle issue?

I'm currently rendering some data by fetching from API within the useEffect hook.

I have a searchValue variable which holds the value the user inputs on the home page search field. This is passed down to this component.

I have set searchValue in the useEffect dependencies so that when it changes it will run the effect again.

When it mounts, it seems to be skipping the !res.ok if statement. I have logged the res.ok to the console outside of this if statement and with each character inputted into the searchValue it always comes back true. The response status is always 200 after a character press so it never runs the !res.ok if statement block. Something must be wrong with my understanding of the lifecycle or asynchronous calls.

I am getting the error: countriesData.map is not a function - so it is trying to render the map on invalid data however this should not even return since I have if (error) written first within the Content function. If this is matched it should return the error message instead, but this is skipped and the countriesData is updated with invalid data. My code is below, please help! I feel like I'm missing something simple and misunderstanding some fundamentals of React!

import { useEffect, useState } from 'react'
import CountryCard from '../CountryCard'
import { countries } from './CountriesList.module.css'

const CountriesList = ({ searchValue }) => {
    const [error, setError] = useState(false)
    const [loading, setLoading] = useState(true)
    const [countriesData, setCountriesData] = useState([])

    useEffect(() => {
        const getCountries = async () => {
            let res = await fetch('https://restcountries.com/v2/all')
            if (searchValue !== '') {
                res = await fetch(
                    `https://restcountries.com/v2/name/${searchValue}`
                )
            }

            if (!res.ok) {
                console.log(res)
                return setError(true)
            }

            const data = await res.json()
            setCountriesData(data)
            setLoading(false)
        }

        getCountries()

        // return () => setLoading(true)
    }, [searchValue])

    const Content = () => {
        if (error) {
            return <div>Error: please check the country you have typed</div>
        }

        if (loading) {
            return <div>Loading...</div>
        }

        return (
            <section className={`${countries} columns is-multiline`}>
                {countriesData.map((country) => (
                    <CountryCard {...country} key={country.name} />
                ))}
            </section>
        )
    }

    return <Content />
}

export default CountriesList
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think you must be mistaken about the shape of countriesData. You initialise it to an empty array, so .map will work on that. Then the only place you change it is setCountriesData(data) - so this must not be an array.

about 4 years ago · Juan Pablo Isaza Report

0

If you are sure that you are setting array to countriesData, then you can fix by just adding Optional chaining syntax.

replace countriesData.map with

countriesData?.map

Optional chaining

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!