componentDidUpdate creates infinite loop and not sure how to avoid it

Viewed 75

Hi I am calling componentdidupdate in order to re-render my page with new ToDos like so


        this.state = {
            displayToDos: false,
            displayLanding: true,
            todo: {
                title: '',
                task: ''
            },
            todos: [],
            createdToDo: null,
            updateModal: false
        }
    }

    async componentDidMount() {
        this.fetchItems()
    }

    componentDidUpdate(prevState) {
        if (prevState.todos !== this.state.todos) {
            this.fetchItems()
        }
    }

    fetchItems = async () => {
        try {
            const todos = await getItems()
            this.setState({ todos })
            console.log('set state of todos', this.state.todos)
        } catch (err) {
            console.error(err)
        }
    }


my intended behavior for my app is that the component mounts fetches the items and sets them to state, and then whenever I make a post, update or delete call the state of todos changes and it fires off the fetch call to re render the todos on the page. However I am getting an infinite loop, how do I fix this?

1 Answers

You can compare arrays like this: let arraysEqual = JSON.stringify(todo) == JSON.stringify(todo1); Or I will suggest you use this library Loadsh you can use the .isEqual method to check the arrays.

Related