0

I am creating a companies page in my application. The url is as follows: example.com/companies/google

I am getting the data from an API running localhost 4000 and, when it returns that data, it is returning this in the console. enter image description here

While this is fine, it seems if I want to set my state to just the one object I would have to do something like this.setState = { company: res.data[0] }. To me it seems like there would be a better way to do this considering it will only ever return one object. Sidenote: I am just now entering in the Javascript/react world so excuse me if im missing the obvious here. Below is just the component mount function that returns the response data in the console.

Is there a better way to set the state of the company rather than setting it based on the first index in the array it returns?

componentWillMount() {
    axios
      .get(`http://localhost:4000/companies/${this.props.match.params.name}`)
      .then(res => {
        console.log(res.data);
      });
  }
1
  • that seems like the API needs to be changed. What is your question? Commented Nov 1, 2018 at 19:07

2 Answers 2

1

This is perfectly acceptable if you know you always want the first result. Sometimes APIs are weird or designed to be consumed as lists, but we always know we want the first result. The only thing you might also want to check is if res.data could ever be null or undefined, to avoid an error:

if (res.data) {
  this.setState({ company: res.data[0] })
}

Sign up to request clarification or add additional context in comments.

Comments

0

Generally you want to separate your data interactions from your components as much as possible.

I'd suggest creating a service that wraps your api and returns data to your components in the format you'd like.

Place something like the code below into another .js file and import it into your component:

export default class companyService {
    get(companyName) {
          return axios
      .get(`http://localhost:4000/companies/${companyName}`)
      .then(res => {
        return res.data[0];
      });
    }

}

Then in your componentWillMountMethod call companyService.get(this.props.match.params.name)

Comments

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.