2

I am creating my first ReactJS front-end application and am running into a problem. When I try to call my setState function (or any other function for that matter) with this. before it inside an if block, I get the error.

Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined

When I call the functions inside my didComponentMount() everything is fine so I think the problem is the if block. I have tried several solutions on different questions but none have an if block so it doesn't work for me.

Function that throws error:

getFilteredTrades() {
        if(document.getElementById("switch").checked){
            fetch("http://localhost:8080/trades/filter?plaform=NintendoSwitch").then(rse => rse.json()).then(
                result => {
                    this.setState({trades: result});
                }
            )
        } else if (document.getElementById("playstation").checked) {
            fetch("http://localhost:8080/trades/filter?platform=PlayStation").then(rse => rse.json()).then(
                result => {
                    this.setState({trades: result});
                }
            )
        } else if (document.getElementById("xbox").checked) {
            fetch("http://localhost:8080/trades/filter?platform=XBox").then(rse => rse.json()).then(
                result => {
                    this.setState({trades: result});
                }
            )
        } else if (document.getElementById("pc").checked) {
            fetch("http://localhost:8080/trades/filter?platform=PC").then(rse => rse.json()).then(
                result => {
                    this.setState({trades: result});
                }
            )
        } else {
            alert("No filter is selected, so all trades will be displayed.")
            this.getAllTrades();
        }
    }

Both setState, and getAllTrades will throw errors here.

getAllTrades():

getAllTrades() {
        fetch("http://localhost:8080/trades/all").then(rse => rse.json()).then(
            result => {
                this.setState({trades: result});
            }
        )
    }

constructor:

constructor(props){
        super(props);

        this.state = {
            trades: []
        }
    }

didComponentMount, where getAllTrades DOES WORK:

componentDidMount() {
        this.getAllTrades();
    }

Does anyone know a solution to this problem? Thanks in advance.

0

2 Answers 2

0

In your getFilteredTrades and getAllTrades functions this refers to the functions itself and not the object and those functions don't have a member setState.

You can resolve the problem in two ways:

  1. Declaring them as arrow functions which does not bind this by writing getFilteredTrades = () => { ... } and getAllTrades = () => { ... }.
  2. Bind the this keyword of the functions to the class object by writing this.getFilteredTrades = this.getFilteredTrades.bind(this) and this.getAllTrades = this.getAllTrades.bind(this) in your constructor.
Sign up to request clarification or add additional context in comments.

5 Comments

Both these solutions lead to a new error in my render function, saying that this.state.trades.map() is not a function.
Well, then you expect this.state.trades to be an array, but it is not. Check what you get from your fetch functions.
@Peter_Lehnhardt When I log it to my console, it does show an array as far as I'm concerned...
Can you call console.log(this.state.trades, this.state.trades instanceof Array) right before calling this.state.trades.map( ... )?
My bad, this was not the issue at all. I mistyped "platform" in the first fetch url and that's why it didn't return an array. Turns out your solution works, thanks!
0

Seems, you're losing a context at some point. Try bind your methods or make them arrow functions:

getAllTrades=()=>{...}

If it doesn't help, try to combine it with self=this trick, which was suggested above

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.