Home > front end >  React-select initial value not being set when retrieved from postgres table
React-select initial value not being set when retrieved from postgres table

Time:10-03

I am using react-select and I am trying to set my value prop to pre-existing value for that record.

I am retrieving the data from a postgres db and it is be returned as follows:

"{value:2,label:'Dog'},{value:4,label:'Cat'}"

What I am then attempting to do is push this to an array as follows:

let data = "{value:2,label:'Dog'},{value:4,label:'Cat'}"
let selectValues = []
selectValues.push(data)
console.log(selectValues)

The console log for selectValues array returns the following result when expanding the array in dev tool's console:

0: "{value:2,label:'Dog'},{value:4,label:'Cat'}"

When I then attempt to assign this array to my react-select component value below, the initial values are not being displayed.

The thing is though, if I hardcode the array object as shown against the commented out line, for value, it works.

Not sure what I am missing with my approach above with pushing the string object to my selectValues array.

<Select 
  name="my-select"
  styles={customStyles}
  options={options}
  isMulti={true}
  value={selectValues}
  // value={[{value:2,label:'Dog'},{value:4,label:'Cat'}]}
  placeholder={'Options....'}
/>   

  

CodePudding user response:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. I have the feelings that you are receiving a JSON from the DB, so you have to parse it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

  • Related