Jump to content

Need help! array.includes() or array.indexOf() always returns false/-1

ImGodz
Go to solution Solved by ImGodz,

If this can ever help someone, the problem was that I was declaring reservations like this: 

let reservations = []

But instead you need to use a constant :

const [reservations, setReservations] = useState([])

 

import React, { useState, useEffect} from 'react'
import {Card, ListGroup, ListGroupItem} from "react-bootstrap";
import axios from "axios";
import moment from "moment";
import "moment/locale/fr-ca";
import { Button } from "react-bootstrap";
require("es6-promise").polyfill();
require("isomorphic-fetch");


export default function Recherche(props){
    moment.locale("fr-ca");

    const [data, setData] = useState([])
    const [q, setQ] = useState("")
    const [d, setD] = useState("")
    const [c, setC] = useState(false)
    const [cat, setCat] = useState("")
    const [searchColumns, setSearchColumns] = useState(["emplacement_depart", "emplacement_destination", "ville"])
    //const [reservations, setReservations] = useState([])
    let reservations = []

    useEffect(() => {
        fetch('http://localhost:3001/deplacements')
            .then((response) => response.json())
            .then((json) => setData(json));

    }, []);

    function search(rows) {
        return rows.filter((row) =>
            searchColumns.some(
                (column) =>
                    row[column].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
            )
        );
    }

    const [columns] = useState(["emplacement_depart", "emplacement_destination", "ville"]);

    function searchDate(rows){
        return rows.filter(row =>
         moment(row.date_heure).format('L').toString().split("T")[0].indexOf(d.toLowerCase()) > -1
        );
    }

    function searchCategorie(rows){
        return rows.filter(row =>
        row.categorie_id.toString().toLowerCase().indexOf(cat.toLowerCase()) > -1
        );
    }


    let account = "'"+props.user.account.accountIdentifier+"'" //Get le tokenId de l'utilisateur
    let user_id = null

    //Trouve le id de l'utilisateur avec son tokenId
    axios.get("http://localhost:3001/users/"+account).then(function (response) {
        user_id = response.data.id
    });

    axios.get('http://localhost:3001/reservations', {
        params: {
            user_id: user_id
        }
    }).then(function (response) {

        if (typeof response.data !== 'undefined' && response.data.length > 0) {
            response.data.forEach(e => reservations.push(e.deplacement_id))
            //console.log(reservations)
        }
    });


    const renderCard = (card, index) => {

        let tokenId;
        let cout;
        let estReserver;
        let now = Date.now();
        now = moment(now).subtract(5, 'hour').toISOString();


        axios.get('http://localhost:3001/users', {
            params: {
                userId: card.chauffeur_id
            }
        }).then(function (response) {
            console.log(response.data[0].tokenid)
            tokenId = response.data[0].tokenid;
        });
        /* Affichage date */

        let date = moment(card.date_heure);

        //console.log(date.toISOString(), "    ",now);
        //console.log(card.ville,card.date_heure,"    ", card.date_heure.split("T")[0].toString().toLowerCase(), "    " , date);
        console.log(now, " NOW    ")

        /* Affichage coût */
        if (card.cout == 0 || card.cout == null){
            cout = 'Gratuit';
        }
        else {
            cout = card.cout + "$";
        }


        //Regarde si le déplacement est déja réserver par l'utilisateur


        //Fonction quand l'utilisateur clique sur réserver
        function reserver(){

                //Crée la réservation dans la base de données
                axios.post('http://localhost:3001/reservations', {
                    deplacement_id: card.id,
                    user_id: user_id
                })
                    .then(res => {
                        console.log(res);
                        console.log(res.data);
                    }, (error) => {
                        console.log(error.message);
                    });

                //Modifie le nombre de places disponnibles du déplacement réserver
                    axios.put('http://localhost:3001/deplacements/'+card.id, {
                        categorie_id: card.categorie_id,
                        ville: card.ville,
                        emplacement_depart: card.emplacement_depart,
                        emplacement_destination: card.emplacement_destination,
                        date_heure: moment(card.date_heure).format('L') + ' ' + moment(card.date_heure).format('LTS'),
                        recurrent: card.recurrent,
                        cout: card.cout,
                        nb_places: card.nb_places - 1,
                        chauffeur_id: card.chauffeur_id
                    })
                        .then(res => {
                            console.log(res);
                            console.log(res.data);
                        }, (error) => {
                            console.log(error.message);
                        });
        }

        if (reservations.indexOf(card.id) !== -1){
             estReserver = true;
        }
        else{
             estReserver = false;
        }


        console.log(reservations, reservations.indexOf(card.id), card.id)
        if (card.date_heure > now) {
            if (c && cout != 'Gratuit' || estReserver){return }
            else if (estReserver){return console.log(card.id + ' est reserver.')}
            else {
                return (
                    <Card style={{width: '18rem'}} key={index} className="box" border="dark">
                        <Card.Header>Conducteur : {
                            card.chauffeur_id
                        }</Card.Header>
                        <ListGroup variant="flush" className="infoDeplacement">
                            <p><strong>Ville : </strong>
                                {card.ville}</p>
                        </ListGroup>
                        <ListGroup variant="flush" className="infoDeplacement">
                            <p><strong>Départ : </strong>{card.emplacement_depart}</p>
                        </ListGroup>
                        <ListGroup variant="flush" className="infoDeplacement">
                            <p><strong>Destination : </strong>{card.emplacement_destination}</p>
                        </ListGroup>
                        <ListGroup variant="flush" className="infoDeplacement">
                            <p><strong>Date : </strong>{date.format("dddd")} le {date.format("LL")}</p>
                        </ListGroup>
                        <ListGroup variant="flush" className="infoDeplacement">
                            <p><strong>Heure : </strong>{date.format('LT')}</p>
                        </ListGroup>
                        <ListGroup variant="flush" className="infoDeplacement">
                            <p><strong>Coût : </strong>{cout}</p>
                        </ListGroup>
                        <ListGroup variant="flush" className="infoDeplacement">
                            <p><strong>Places disponnibles : </strong>{card.nb_places}</p>
                        </ListGroup>
                        <Button type={"button"} variant="default" className="btn-reserver"
                                onClick={reserver}>Réserver</Button>
                    </Card>
                )
            }
        }
    }

    return (
        <div>
        <div>
            <div className='row'>
            <label className="rechercheCheckbox">
                Recherche :
            <input type="text" value={q} onChange={(e) => setQ(e.target.value)}/>
            </label>

            {
                columns && columns.map(column => <label className="rechercheCheckbox">
                    <input type="checkbox" checked={searchColumns.includes(column)}
                    onChange={(e) => {
                        const checked = searchColumns.includes(column);
                        setSearchColumns((prev) =>
                        checked
                            ? prev.filter((sc) => sc !== column)
                            : [...prev, column]
                        )
                    }}
                    />
                    {(() => {
                        switch (column) {
                            case "emplacement_depart":   return "Départ";
                            case "emplacement_destination": return "Destination";
                            case "ville":  return "Ville";
                        }
                    })()}
                </label>)
            }
            <label className="rechercheCheckbox">
                <input type="checkbox" onChange={(e) => setC(!c)}/>
                Gratuit
            </label>
            </div>

            <div className='row'>
            <label className='rechercheCheckbox'>Type de déplacement :</label>
            <select value={cat}
                    name="categorie_id"
                    onChange={(e) => setCat(e.target.value)}>
                <option value=''>Choisir...</option>
                <option value='1'>Vers un pavillon</option>
                <option value='2' partir de Victoriaville</option>
                <option value='3'>Inter-pavillons</option>
            </select>

            <label className="rechercheCheckbox">
                Date :
                <input type="date" value={d} onChange={(e) => setD(e.target.value)}/>
            </label>
            </div>
        </div>
        <div className="grid">
            {searchCategorie(searchDate(search(data))).map(renderCard)}
        </div>
    </div>
    );
}

reservations.indexOf(card.id) always returns -1

or

reservation.includes(card.id) always returns false

I have no idea why, please help!

Link to comment
Share on other sites

Link to post
Share on other sites

Can you show the log output for the "reservations" array and "card.id" where you search? Maybe I'm blind but I don't see "card.id" initialized anywhere. Are you certain "card.id === e.deplacement_id" is true?

 

I mean this line in particular:

console.log(reservations, reservations.indexOf(card.id), card.id)

 

The output from that line should give a clue as to whether the ID is actually in there.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Eigenvektor said:

Can you show the log output for the "reservations" array and "card.id" where you search? Maybe I'm blind but I don't see "card.id" initialized anywhere. Are you certain "card.id === e.deplacement_id" is true?

Capture2.PNG.2d55b56079c146f982a8a43d2267c6c1.PNG

This is the output before the renderCard return, it's the array of reservations [2], then reservations.includes(card.id), then card.id

Link to comment
Share on other sites

Link to post
Share on other sites

If this can ever help someone, the problem was that I was declaring reservations like this: 

let reservations = []

But instead you need to use a constant :

const [reservations, setReservations] = useState([])

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×