Shannon Smith
Shannon Smith

Reputation: 81

What is the correct way to add to an array with splice in react

Newbie question.

I have an array that i need to add to and I am using slice to do this. I am using gatsby/react. The problem I have is each time my page/component rerenders the object I am adding to my array gets added again

Here is my code

class IndexPage extends PureComponent {

  render() {
    const data = this.props.data;

    const hostels = data.featuredHostel.edges;

    const hopimage = data.hop.childImageSharp.fluid;
    hostels.splice(8, 0, {
      node: {
        featuredImage: {
          alt: 'Bedhopper Image',
          fluid: hopimage
        },
        id: 'bedhopper',
        slug: '/deals/bed-hopper',
        title: 'For travel adicts who want to stay everywhere'
      }
    });

    return (....

Been stuck on this for a while now. Any help appreciated

Upvotes: 0

Views: 155

Answers (1)

indapublic
indapublic

Reputation: 2328

You should make any calculation on constructor or componentDidMount.

class IndexPage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      hostels: props.data.featuredHostel.edges.concat(...)
    }
  }

  componentDidMount() {

  }

  render() {
    const { hostels } = this.state;

    return (
      ...
    )

Probably, your case can works too (I didn't see whole code). I guess you use array index as key for render

hostels.map((hostel, hostelIndex) => (<SomeComponent key={hostelIndex} />))

You can change key to hostel.id for example for more unique block.

Upvotes: 3

Related Questions