0

I have thunk properly imported and installed in my index.js file. I am trying to set up an action that will render a loading page while it does a fetch, and then a second fetch inside a .then() block. This is because each fetch needs to retrieve data from a rails show page and then use that code to create a JS object and add it to an array. The code is as follows...

return (dispatch) => {
        dispatch({type: 'LOAD_FIGURE'})
        let movesLen = moves.length // Going to be either 2 or 3
        if (movesLen == 2){
            fetch(`http://localhost:3000/moves/show/${moves[0]}`)   // Generate first move
                .then(resp => resp.json())  
                .then(json => console.log(json))    // make this functional later
                .then(fetch(`http://localhost:3000/moves/show/${moves[1]}`)  // Generate the second move
                    .then(resp => resp.json())
                    .then(json => console.log(json)) // make this functional later
                )
        }
    }

This will just return with the following error

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I'm unsure what could be going wrong here, as this fetch is pretty basic. I'm worried it has something to do with the nested fetch, but the fact that I get the error twice also makes me think while it fetches both, both return the same error.

  • 3
    The first thing I would check is that the API endpoint is responding correctly - check this in your network tab within devTools. The error often indicates that HTML (or XML) is being received and processed, hence it finding `<` in the first position of the response. – Bladeski Jun 21 '21 at 09:15
  • 2
    Unrelated to the error, but having nested `.then()` calls is a code smell. [Promises aren't just callbacks](https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks). They were created to avoid having to nest them. – VLAZ Jun 21 '21 at 09:16
  • You're definitely correct, but I need this project to be functional within the week so I need to focus on functionality then move on the fix any code smell afterwards –  Jun 21 '21 at 20:08

1 Answers1

0

You need to tell the server (presumably your Rails app) that you want a JSON response. Rails will default to text/html unless you specify otherwise or add a default in your routes.

This can be done either by setting the Content-Type header:

fetch(`http://localhost:3000/moves/show/${moves[0]}`, {
  headers: {
    'Content-Type': 'application/json'
  }
})

Or by adding an extension to the URL:

fetch(`http://localhost:3000/moves/show/${moves[0]}.json`) ...

This overrides the headers in Rails. Of course you also have to ensure that your Rails app actually responds to the request with valid JSON as well.

max
  • 96,212
  • 14
  • 104
  • 165