-1

i got this problem i need help " this.state.pages.filter is not a function" this is the code -->

class BlockEditor extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        pages: '',
        editor: false,
        page: '',
        pageId: props.match.params.pageId
    }
}

componentDidMount() {
    servicePage.getPage()
        .then( res => {
            this.setState({
                pages : res
            });

            if( this.state.pageId ) {
                this.state.pages.filter(page => page._id === this.state.pageId).forEach(page =>
                    this.setState({
                        page : page
                    })
                )
            }
        })

}
  • 1
    I think ```.filter``` is intended to work only on arrays. Check https://stackoverflow.com/questions/55458675/filter-is-not-a-function/55458751. – dclipca Apr 18 '21 at 17:33
  • Please format your code appropriately to improve the readability of your question. If your question is hard to read, contributors are less likely to help. Also, could you refrain from using "I need help" phrases? They don't really add any useful information to your question. Could you also share what you've tried so far? – Yves Gurcan Apr 18 '21 at 19:31

1 Answers1

1

this.state.pages is initialized as a string.
Here you are trying to use the filter function, that is attached to the prototype of Array:Array.prototype.filter.
The filter function does not exist on strings, that explains the error message.

To fix the issue you should declare pages as an array:

this.state = {
    pages: [] ,
    editor: false,
    page: '',
    pageId: props.match.params.pageId
}
L.Blondy
  • 277
  • 1
  • 6