1

I have a react application, where I use the axios library, to get some values, and set them into an array of javascript objects in my state

  componentDidMount(){
    axios.get('http://localhost:8080/zoo/api/animals')
.then(res => this.setState({animals: res.data}))
}

Now I want to check if the objects, contains an Owner object, inside it, and filter out does that does,

First, I tried making a const, and then using the filter, to check if they contain the objects, and then set the state, but I can't save my values in a local variable

  componentDidMount(){
const animals= [];
axios.get('http://localhost:8080/zoo/api/animals')
.then(res => animals=res.data)
console.log(animals) // logs empty array
console.log('mounted') 
  }

how can I make it so, that I can only get the animals that do NOT, have an owner object inside it?

Example with owner

4
  • 2
    animals is empty because axios.get is asynchronous. You need to perform the filter inside a then callback Commented Jan 9, 2019 at 22:07
  • Ahh that makes sense, thank you! Commented Jan 9, 2019 at 22:07
  • 2
    In any case, that doesn't answer your original question - have you tried to filter the results? Commented Jan 9, 2019 at 22:10
  • You're right @chazsolo but a great answer was provided Commented Jan 9, 2019 at 22:15

1 Answer 1

4

Your animal array is empty in your second example because axios.get is asynchronous, what is in your then will be executed once the data is fetch, but the function will keep on going in the meantime.

To filter out your array, simply use filter right after fetching your data :

componentDidMount(){
    axios.get('http://localhost:8080/zoo/api/animals')
        .then(res => this.setState({animals: res.data.filter(animal => !animal.owner)}))
}

This function will filter out every animal object that does not have an owner property.

Working example :

const animals = [
	{
		name: 'Simba',
		owner: {
			some: 'stuff'
		}
	},
	{
		name: 1
	}, ,
	{
		name: 2
	}, ,
	{
		name: 3,
		owner: {
			some: 'stuff'
		}
	},
	{
		name: 'Bambi'
		//status: 'dead'
	}
]

console.log(animals.filter(animal => animal.owner))

EDIT: the answer was changed so that it only filters animals, that does not have an owner

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

2 Comments

I wanted to make it so, that i only have animals that does not have an owner though
Sorry, I missunderstodd the question, simply put an exclamation point before the condition : filter(animal => !animal.owner). That should do it

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.