if else statement not working in react component

Viewed 198

I am trying to implement a condition in my react component . When the user triggers the onClick the state updates allStakes creating one array of 4 values. The problem is that I do not want the user to input more than 4 values so tried to give the limit by doing an if else statement. I tried to add a console.log in both statements.The weird fact is that setState get updated but the csonole.log is never displayed.The component keeps rendering all the values that I insert even if the array is longer than 4. Thanks in advance

import React, { Component } from 'react';
import Stake from './stake';

class FetchRandomBet extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            bet: null,
            value: this.props.value,
            allStakes: []
        };
    }

    async componentDidMount() {
        const url = "http://localhost:4000/";
        const response = await fetch(url);
        const data = await response.json();

        this.setState({
            loading: false,
            bet: data.bets,
        });
    }

    render() {
        const { valueProp: value } = this.props;
        const { bet, loading } = this.state;
        const { allStakes } = this.state;

        if (loading) {
            return <div>loading..</div>;
        }
        if (!bet) {
            return <div>did not get data</div>;
        }
        return (
            < div >
                {
                    loading || !bet ? (
                        <div>loading..</div>
                    ) : value === 0 ? (
                        <div className="bet-list">
                            <ol>
                                <p>NAME</p>
                                {
                                    bet.map(post => (
                                        <li key={post.id}>
                                            {post.name}
                                        </li>
                                    ))
                                }
                            </ol>
                            <ul>
                                <p>ODDS</p>
                                {
                                    bet.map(post => (
                                        <li key={post.id}>
                                            {post.odds[4].oddsDecimal}
                                            <div className="stake-margin">
                                                <Stake
                                                    onClick={(newStake) => {
                                                        if (allStakes.length <= 3) {
                                                            this.setState({ allStakes: [allStakes, ...newStake] })
                                                            console.log('stop')
                                                        } else if (allStakes.length == 4) {
                                                            console.log('more than 3')
                                                        }
                                                    }}
                                                />
                                            </div>
                                        </li>
                                    ))
                                }
                            </ul>
                        </div>
3 Answers

May be it happens because of incorrect array destructuring. Try to change this code:

  this.setState({ allStakes: [allStakes, ...newStake] })

by the next one:

 this.setState({ allStakes: [newStake, ...allStakes] })

Your state belongs to your FetchRandomBet component and you are trying to update that from your imported component. There are 2 solutions to that.

1> Wrap your Stake component to a separate component with onClick handler something like this

<div onClick={(newStake) => {
    if (allStakes.length <= 3) {
        this.setState({
            allStakes: [allStakes, ...newStake
            ]
        })
        console.log('stop')
    } else if (allStakes.length == 4) {
        console.log('more than 3')
    }
}}><Stake /></div>

Or

2> Pass the state as a prop to the Stake component which will be responsible to update the state for FetchRandomBet. something like this

<Stake parentState={this}/>

And inside the Stake component change the parentState on click of wherever you want.

I solved the problem. I transfered the onClick method in stake component and I handled the upload of the common array with an array useState. I add the value to newStake and when I click ok I retrieve newStake and spread it into a new array and then I check that array. If there is a value should not keep adding otherwise it can add values. It works fine. Thanks anyway

import React, { useState } from 'react';
import CurrencyInput from 'react-currency-input-field';

function Stake(props) {
    const [newStake, setStake] = useState(null);
    const [allStakes, setStakes] = useState(null);

    const changeStake = (e) => {
        setStake([e.target.value])
    }

    const mySubmit = () => {
        if (!allStakes) {
            setStakes([...newStake, allStakes])
            props.onClick(newStake);
        } else if (allStakes) {
            console.log('stop')
        }
    }

    return (
        <>
            <CurrencyInput
                onChange={changeStake}
                style={{
                    marginLeft: "40px",
                    width: "50px"
                }}
                placeholder="Stake"
                decimalScale={2}
                prefix="£"
            />
            <button onClick={mySubmit}>yes</button>
            <button>no</button>
            {newStake}
        </>
    );
}

export default Stake;
Related