BennKingy
BennKingy

Reputation: 1593

How to create fallback if value is not found in JSON when saving to state React

This is my get request which grabs a few different JSON end points:

// Grabs the posts from the json url
private getPosts() {
   axios
      .get( this.getCompanyUrl() )
      .then(response =>
        response.data.map(post => ({
          id: `${ post.Id || post.jobId }`,
          name: `${ post.Name || post.advertisements[0].title.localization[0].value }`,
          name2: `${ post.Name || post.title.localization.pop().value }`, 
          //location: `${ post.Location || post.department.title.localization[0].value || 'Fall back location' }`,
        }))
      )
      .then(posts => {
        this.setState({
          posts,
          isLoading: false
        });
      })
       // Error catching
      .catch(errors => this.setState({ errors, isLoading: false }));
}

If a location is not found in the JSON, I want to add a fallback location, however it does not seem to be working:

Line 214 >> location: `${ post.Location || post.department.title.localization[0].value || 'Fall back location' }

I receive this error, even when there should be a fall back working:

TypeError: Cannot read property 'title' of undefined at JsonFeed.tsx:214 at Array.map () at JsonFeed.tsx:210

Any ideas where I am going wrong?

Upvotes: 0

Views: 641

Answers (1)

Josep
Josep

Reputation: 13071

If your app supports optional chaining then you could do it like this:

post.Location || post.department?.title?.localization?[0]?.value || 'Fall back location'

Otherwise, you could use the old-school style:

post.Location ||
(
  post.department &&
  post.department.title &&
  post.department.title.localization &&
  post.department.title.localization[0] &&
  post.department.title.localization[0].value
) ||
'Fall back location'

Upvotes: 1

Related Questions