Home > Net >  can't seem to get this array to work with splice
can't seem to get this array to work with splice

Time:10-30

I am trying to get a new fortune to get included into my array when someone submits a fortune but I can't get it to work now matter what im trying. Do I like it to the other file where someones submit their fortune, or am I messing up somewhere else?

import React from "react";
import {Link} from "react-router-dom"
import AddFortune from "./add-fortune";

class Fortune extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        fortunes: [
            "An exciting opporunity lies ahead",
            "A long time friend will brirng wise advice in the coming week",
            "You will find great fortunes in unexpected places",
            "Never give up... Unless you want to thats cool too",
            "111",
            "222",
            "333",
            "444",
            "Maybe a nap is what you need",
            "Don't Text Your EX!"
        ],
        array.push('
        fortune: "" ');
        array.splice(array.length, 0, '{fortune:""}');
        array[array.length] = fortune: "";
    }
}

componentDidMount() {
    this.getFortune();
}

getFortune = () =>  {
    let rand = Math.floor(Math.random() * (this.state.fortunes.length)   0)
    console.log(rand);
    this.setState({
        fortune: this.state.fortunes[rand]
    })
}



render() {
    return (
        <body>
        <div className="home-buttons-wrapper">
            
            <button onClick={this.getFortune}>Your Fortune</button>
            
            
        </div>
        <h5>{this.state.fortune}</h5>
        </body>
    )
}
}

console.log('getFortune');

export default Fortune; 

What im trying to get to be added to the fortunes file

import React, { Component } from 'react'

export default class AddFortune extends Component {
    constructor(props) {
        super(props)

        this.state = {
            nameInput: "",
            loading: false,
            error: false
        }

        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
    }

    handleChange(event) {
        this.setState({ [event.target.name]: event.target.value })
    }

    handleSubmit(event) {
        event.preventDefault()

        this.setState({
            loading: true,
            error: false
        })

        fetch("https://backend-edwin.herokuapp.com/item/add", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({
                name: this.state.nameInput
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.id) {
                this.props.history.push("/fortune")
            }
        })
        .catch(error => {
            console.log("Error adding fortune ", error)

            this.setState({
                loading: false,
                error: true
            })
        })
    }

    render() {
        return (
            <div className='add-item-wrapper'>
                <h2>Add Fortune</h2>

                <form onSubmit={this.handleSubmit}>
                    <input 
                        type="text" 
                        placeholder="fortune"
                        name="nameInput" 
                        value={this.state.nameInput}
                        onChange={this.handleChange}
                    />

    
                    <button type="submit" disabled={this.state.loading}>Add Fortune</button>
                </form>

                {this.state.loading ? <div className="loading">Submitting...</div> : null}

                {this.state.error ? <div className="error">An error occured... Please try again later.</div> : null}
            </div>
        )
    }
}

CodePudding user response:

Here is a method to get a random fortune from a list of fortunes.

import React from "react";

class Fortune extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        fortunes: [],
        fortune: '',
        loading: true,
        error: false
    }
}

componentDidMount() {
    fetch("https://backend-edwin.herokuapp.com/item/", {
        method: "GET",
        headers: { "content-type": "application/json" },
    })
    .then(response => response.json())
    .then(data => {
      this.setState({
        loading: false,
        fortunes: data, //check how the data is coming from api and add the variable here if  fortunes list `if data.fortunes` then add data.fortunes here 
        error: false
      }, this.getFortune)
    })
    .catch(error => {
        console.log("Error fetching fortune ", error)
        this.setState({
            loading: false,
            error: true
        })
    })
  }

getFortune = () =>  {
    let rand = Math.floor(Math.random() * (this.state.fortunes.length - 1)   0)
    console.log(rand);
    this.setState({
        fortune: this.state.fortunes[rand]
    })
}



render() {
   if(this.state.loading) {
     return (<div>Loading .....</div>)
   }
   if(this.state.error) {
    return (<div>Error occurred in API</div>)
  }
    return (
        <div>
        <div className="home-buttons-wrapper">
            
            <button onClick={this.getFortune}>Your Fortune</button>
            
            
        </div>
        <h5>{this.state.fortune}</h5>
        </div>
    )
}
}
export default Fortune
  • Related