javascriptreactjsreact-nativejsx

How to append data to state array?


I have an API that responds with a list of users. I use filters on the users. I use state in my API request and some of it contains arrays.

Currently, my code is replacing the old state with the new one. Instead of replacing the old state, how do I add selected filters to an array?

This is my state:

this.state = {
  loading: false,
  dataSource: [],
  error: null,
  topics: []
}

This is my API call:

getLawyers = () => {
  fetch(
    'https://www.someapi.com/posts?topics[]=' + this.state.topics,
    { method: 'GET' }
  ).then((response) => response.json())
  .then((responseJson) => {
    this.setState({
      loading: false,
      error: responseJson.error || null,
      dataSource: responseJson.data,
      dataSource: [
        ...this.state.dataSource,
        ...responseJson.data
      ],
      loadingMore: false
    });
  }).catch((error) => {
    this.setState({error, loading: false});
  });
}

and this is where the user selects topics to search:

<Text onPress={(text) => this.setTopic('topic1')}> Some Topic </Text>
<Text onPress={(text) => this.setTopic('topic2')}> Some Topic </Text>
<Text onPress={(text) => this.setTopic('topic3')}> Some Topic </Text>

setTopic():

setTopic(searchedTopic) {
  this.setState({topics: searchedTopic});
}

Solution

  • searchedTopic is a string and not an array, therefore the correct answer should be:

    setTopic(searchedTopic) {
     this.setState({topics: [ ...this.state.topics, searchedTopic ] });
    }
    

    With ...searchedTopic each character would be added to the state topics. E.g.

    ["topic1", "topic2", "t", "o", "p", "i", "c", "3"]