0

I am new to react and I have designed a drop-down menu using react-select

const Locations = [
  { label: "Albania", value: 355 },
  { label: "Argentina", value: 54 },
  { label: "Austria", value: 43 },
  { label: "Cocos Islands", value: 61 },
  { label: "Kuwait", value: 965 },
  { label: "Sweden", value: 46 },
  { label: "Venezuela", value: 58 }
];

<Select placeholder='Select from pre-created Tags 'onChange={handleDropDown('Tags')} defaultValue={values.Tags} required options={Locations}/>

and I have received some data drom an api using axios:

 state = {
    locations:[],
    departments: [],
    tagsList:[],
  }

axios.get('/api/jobs/list-tags',{headers:headers}).then(respo =>{
      console.log(respo.data)
      this.setState({
        tagsList:respo.data
      })
      console.log(this.state.tagsList)

the data received from the api looks like this:

Object { id: 1, name: "MongoDB" }
Object { id: 2, name: "JavaScript" }

I want to replace the hardcoded data in Locations array with the info received from the api in the same format. (instead of { label: "Albania", value: 355 }, { id: 2, name: "JavaScript" }). how can I achieve this?

1 Answer 1

2

You can map the response data:

      this.setState({
        locations: respo.data.map(t=>({label: t.name, value: t.id}))
      })
Sign up to request clarification or add additional context in comments.

6 Comments

yeah but what would I put here? options={Locations}
I mean locations not tagsList, my mistake.
yes but since this is in the setState, it gives me an error if I write it like options={locations} for example. ('locations' is not defined.) should it be like this.state.locations?
Yes, It should be this.state.locations
@VahidAlimohamadi the introduction to the solution sounded condescending, I replaced it with a link to documentation...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.