0

In weather api, some values are null which is displayed as undefined on main page (See the image at the bottom), which takes maximum space. How to replace these null values with empty i.e ' ' or 'NA'?

Below is the code

fetch(`${IP_LOCATION}&lat=${lat}&long=${lon}`)
  .then(res => res.json()).then(responseJson => {
    try {
      this.setState({
        sunrise: responseJson.sunrise,
        sunset: responseJson.sunset,
        // Here I get undefined
        moonrise: responseJson.moonrise,
        moonset: responseJson.moonset,
      })

    } catch {
      toast.error('No Data Received')
    }

  });

enter image description here

Any solution?

2 Answers 2

4

quick solution:

try {
      this.setState({
        sunrise: responseJson.sunrise,
        sunset: responseJson.sunset,

        // replace with this line 
        moonrise: responseJson.moonrise ? responseJson.moonrise : " ",

        moonset: responseJson.moonset,
      })

    } catch {
      toast.error('No Data Received')
    }

(edit) using the ternary operator you can check for null or undefined and override with value of your choice

Sign up to request clarification or add additional context in comments.

5 Comments

Correct me if I'm wrong, but I don't think A ? A : B is an elvis operator, but a basic ternary. Elvis is A ?: B isn't it?
Hey guys... Its still returning undefined
I tried with the solution mentioned by @GiuseppeB, but, still no effect
any chance is a binding issue? what if you replace "" with any char, as "-"?
you can try to bind the var using the elvis operator (this time elvis for real) . {{state?.moonrise}}
1

You could use the ternary operator as @GiuseppeB mentioned. Or you can use an or operator like this responseJson.moonrise || "". Keep in mind with this solution, however, that if responseJson.moonrise is ever a falsy value (not just null or undefined) then the empty string will be the result.

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.