Home > Software engineering >  Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern in ReactJS W
Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern in ReactJS W

Time:02-28

I'm building a website using ReactJS that uses JSON present locally on my computer to fetch the information to be filled out. Here is the index.js file: -

import React from 'react';
import data from 'notes.json';

class BlogList extends React.Component {
    constructor(props){
        super(props);

        this.state={
            items:[],
            loaded: false
    };

}

/* useEffect()=>{
return function(){

}
},[deep])
*/      //Similar to ComponentDidUnMount();

componentDidMount(){
    fetch(data)
    .then(response => response.json())
    .then(json => {
        this.setState({
            items: json,
            loaded: true,
        })
    })
    
 }

    render() {
        const {items, loaded} = this.state;

       if(!loaded){
            return <h3>Loading........</h3>
        }
        return (
            <div className="content-container" >
            {   
                items.map((item)=>(
                    <div key={item.id}>

                        <p>
                            {item.postId}
                        </p>
                        <p>
                            {item.id}
                        </p>
                        <p>
                            {item.name}
                        </p>
                        <p>
                            {item.email}
                        </p>
                        <p>
                            {item.body}
                        </p>
                        <hr/>
                    </div>
                ))

            }
        </div>
        );
    }
}

export default BlogList;

And the JSON file is here: -

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
  },
  {
    "postId": 1,
    "id": 3,
    "name": "odio adipisci rerum aut animi",
    "email": "[email protected]",
    "body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
  },
  {
    "postId": 1,
    "id": 4,
    "name": "alias odio sit",
    "email": "[email protected]",
    "body": "non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati"
  }
]

It is constantly giving me this error in the console: - Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.

CodePudding user response:

You may get this error if the server's response is text but you attempt to parse it as JSON using res.json().

fetch(serverUrl, {method: 'GET'})
.then((res) => res.json())
res.text() 

is appropriate if the server returns text.

In this situation Safari once gave me the OP's error, but Chrome was more specific: "unexpected token W in json at position 0" -- res.json() expects the first character of the string to be { or [ since that is how JSON begins.

Or, as Safari would say, "the string did not match the expected pattern."

  • Related