Cannot set property 'x' of undefined

Viewed 216

I want to set variable at store. Here is my store

class storeCategory{

    @observable categories =[];

    @action getCategories = () =>{
        fetch('http://localhost:3000/categories')
        .then((resp) => resp.json())
        .then(function(resp2){
            this.categories=resp2;
        });
    }


}

here is my component

@inject('sCategory')
@observer
class Category extends React.Component{

    componentDidMount=()=>{
       this.props.sCategory.getCategories();
    }

    render(){
        const {sCategory} = this.props;
        return (
            <ListGroup>
                {this.props.sCategory.categories.map((cat, index) => {
                            return (
                                <ListGroupItem key={cat.id}>{cat.categoryName}</ListGroupItem>
                            )
                        })}
            </ListGroup>
          );
    }
}

I add to sCategory to Provider at index.js

Im getting this error at this.categories=resp2 in fetch method;

Cannot set property 'categories' of undefined

1 Answers

Use arrow function instead:

@action getCategories = () =>{
    fetch('http://localhost:3000/categories')
    .then((resp) => resp.json())
    .then((resp2) => {
        this.categories=resp2;
    });
}`

function keyword binds "this" keyword to itself, but arrow function keeps it bound to the context

Related