0

I want to access the value of state/property in new state prop. Actually I have already state property where I am storing value of Item=5 and I create UrlParam Where I am storing URL but I need Item numeric value in URL property. I am new to React , Somebody please help me how to do this ?

I am not getting number value currently I am getting string. You may see in attachment .

Code

    this.state={    
    Item : 5,
    Skip:0,
    urlParams:'http://localhost:3001/meetups?filter[limit]=Item&&filter[skip]=Skip'
    }
Andrew
  • 93
  • 3
  • 12

2 Answers2

2

Set it after.

this.state={    
    Item : 5,
    Skip:0,
    urlParams:''
}

this.setState({ urlParams: 'http://localhost:8001/parties?filter[limit]=' + this.state.Item + '&filter[skip]=' + this.state.Skip })

OR

this.setState({ urlParams: `http://localhost:8001/parties?filter[limit]=${this.state.Item}&filter[skip]=${this.state.Skip}` })

You could also create functions to update the url anytime the Item or Skip value changes

updateItem(newValue) {
   this.setState({ 
      Item: newValue, 
      urlParams: `http://localhost:8001/parties?filter[limit]=${newValue}&filter[skip]=${this.state.Skip}`
   })
}
varoons
  • 3,807
  • 1
  • 16
  • 20
1

If I've understood you correctly, you want to use the Item state in your urlParams state. This cannot be done in the state declaration without using some sort of helper function, so a better alternative is to call setState() in order to declare urlParams after the fact.

In a React component, this may look something like:

state = {
  Item: 5,
  Skip: 0,
  urlParams: "",
}

componentDidMount() {

  ...

  this.setState((prevState) => { 
    urlParams: `filter[limit]=${prevState.Item}&&filter[skip]=${prevState.Stem}`
  }

  ...

}

It may seem like a hastle if you're new to React, but it's the best way to go since you should never modify state directly.

// good
this.setState((prevState) => ...)

// bad
this.state.urlParams = `...`

Read this section of the docs for more info.

leander
  • 534
  • 1
  • 4
  • 18
  • 1
    You shouldn't have to splat `prevState` when using `setState`, because react does that for you, iirc... (unless you want to overwrite `urlParams` with the previous value if it is set...) – Garrett Motzner Mar 20 '19 at 20:08