modg
22 July 2021 12:04
1
Hey everyone,
Another day, another question 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
Johan
22 July 2021 12:59
2
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
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
modg
22 July 2021 13:16
3
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
modg
22 July 2021 13:24
4
Okay… stupid mistake on my part
The ids
IS an array, until I run my action, where ids: id
is changing it from an array to an object
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
1 Like