Thomas Allen
Thomas Allen

Reputation: 811

How to set component state conditionally

I have this as my main App component, which works, but only if there is localStorage data.

I am struggling to find a way to set the state to an empty array if localStorage is empty. Any help on how to do this would be really appreiciated! I've tried a number of different conditional statements but not of them seem to work.

export default class App extends Component {
  constructor(props){
    super(props);
    // set variable as data from local storage
    const storageData = JSON.parse(localStorage.getItem('listItems'));
    console.log(storageData);

    // set initial state
      this.state = {
        value: '',
        url: '',
        // set items array as storage data variable
        // bug: Page only loads if localstorage available
        items: storageData
      }
    this.removeItem = this.removeItem.bind(this);
  }

Upvotes: 0

Views: 227

Answers (2)

Matthew Barbara
Matthew Barbara

Reputation: 3962

A simple condition should work just fine.

  this.state = {
    value: '',
    url: '',
    // If storage is not null or undefined use it,
    // otherwise use an empty array
    items: storageData || []
  }

Upvotes: 3

Tholle
Tholle

Reputation: 112887

localStorage.getItem('listItems') will return null if listItems doesn't exist in localStorage yet, so you could check for that before parsing the JSON.

const storageData = localStorage.getItem('listItems');
const parsedStorageData = storageData ? JSON.parse(storageData) : [];

this.state = {
  value: '',
  url: '',
  items: parsedStorageData
}

Upvotes: 2

Related Questions