Using .includes() with state.theme array

Hey everyone,

Another day, another question :grin: thanks as always for any time anyone can spare to help me with this. I think this is a pretty straight forward one.

I’m setting an array in my theme state, like this:

export default {
  // ...
  state: {
    theme: {
      samples: {
        ids: ['test', 'example', 'etc'],
      },
    },
  },
  // ...
}

And in a connect-ed component, I’m doing something like this:

import React from 'react'
import { connect } from 'frontity'

const MyComponent = ({ state }) => {
  const { samples } = state.theme
  
  if(samples.ids.includes('test')) {
    console.log('It includes test')
  } else {
    console.log('It doesn\'t include test')
  }

  return <p>This is just an example</p>
}

export default connect(MyComponent)

But this results in an error, as technically samples is an object not an array; it’s the result of the returned promise that includes the array.

So my question is, how do I access the array in [[Target]] to check if it includes something?

Thanks

It should work, since ids is an array.

const state = {
  theme: {
    samples: {
      ids: ['test', 'example', 'etc'],
    },
  }
};
console.log(state.theme.samples.ids.includes('test'));
// returns true

const { samples } = state.theme
console.log(samples.ids.includes('test'));
// returns true

So I guess either Frontity is doing something weird with the array (which I doubt), or ids is not an array as in your example :wink:

update:
Just checked with an array in my own code by checking it in the console, and .includes('') works as expected, even when deep in the Frontity object. Haven’t checked in React though, but since it uses the same object it shouldn’t cause any issues.

1 Like

Thanks @Johan

If I run this:

  const { samples } = state.theme;
  console.log(samples.ids);
  console.log(typeof samples.ids);

I get this

Is this what you’d expect to see when running console.log(state.theme.whatever)?

Here’s my actual theme index file which might help

Okay… stupid mistake on my part :sweat_smile:

The ids IS an array, until I run my action, where ids: id is changing it from an array to an object :roll_eyes:

It should look like this:

  actions: {
    theme: {
      addSample:
        ({ state }) =>
        (id) => {
          state.theme.samples = {
            ...state.theme.samples,
            ids: [...state.theme.samples.ids, id],
          };
        },
      // ...
    },
  },

And that solves the problem. Apologies for wasting time :smiley:

1 Like