Search code examples
reactjsfluxwebpack-dev-serverbabeljs

How to fetch an object array from Flux dispatcher in React?


On my front-end I'm running React with Flux dispatchers. I have web-pack-dev server running also.

After researching "Unexpected Token" errors, I continually arrive at this solution: babel-loader jsx SyntaxError: Unexpected token

However, I have this preset included in my webpack.config.js file and I only get this error when including an array in the dispatcher from flux. I've included the function I built for testing below. This works perfectly with only passing one object, but it throws an error when an array is passed.

Module build failed: SyntaxError: /Users/foo/sites/app/js/actions/TripActions.js: Unexpected token (33:6)
  31 |              country: "Spain",
  32 |              complete: false
> 33 |          },
     |           ^
  34 |          {
  35 |              id: 987655432,
  36 |              text: "Another Great Flat!",

My function that I am testing

export function reloadTrip() {

    dispatcher.dispatch({type: "FETCH_TRIPS"});

    setTimeout(() => {


        dispatcher.dispatch({type: "RECIEVE_TRIPS", [
            {
                id: 123456789,
                text: "Nice flat for you and me",
                city: "Madrid",
                country: "Spain",
                complete: false
            },
            {
                id: 987655432,
                text: "Another Great Flat!",
                city: "Paris",
                country: "France",
                complete: true
            }
       ]});


    }, 1000);
}

Solution

  • You're passing an object to dispatcher.dispatch, but the object has a key/value ({type: 'RECEIVE_TRIPS'}) and an array ([{...}, {...}]). The array is invalid, an object needs a key/value.

    Pass:

    {
        type: 'RECEIVE_TRIPS',
        trips: [{...}, {...}],
    }
    

    and you should do better.

    To test if Babel is working as expected, try it on the command line with an error free (ie: simple) script.