RashadArbab
RashadArbab

Reputation: 105

Why isn't my list rerending when I update the list

I'm looking for a way to update my watchlist after someone adds to the watchlist. So far it is doing that but it's not visually re-rendering the watchlist. If I refresh the page though the updated watchlist is showing, I was hoping for a method where I don't have to do something like window.refresh(). I read that using states would resolve this problem, but I am using useState for watchlist and when I set watchlist to the new watchlist it's not re mapping and showing the new watchlist.

Additionally: if you guys have any recommendations on how I should handle the local storing of passwords and emails that would be helpful I am trying to build this website for production and for people to use so anything that makes it faster, smoother, and more secure helps.

import axios from 'axios';
import Navbar from './LoginNavbar';
import { UserContext } from './UserContext';
import React, { useContext, useState, useEffect, map } from 'react'
import TradingViewWidget from 'react-tradingview-widget';
import { createChart } from 'lightweight-charts'
import TestPage from './TestPage';
import classnames from 'classnames';
import { validateFields } from './Validation';
import Cookies from 'js-cookie';
import '../css/Watchlist.css';
function Watchlist() {

    var data = (['test 1', 'test 2']);




    const [ticker, setTicker] = useState('');
    const [run, setRun] = useState(0);

    const [user, setUser] = useState({
        name: sessionStorage.getItem('sessionName'),
        email: sessionStorage.getItem('sessionEmail'),
        password: sessionStorage.getItem('sessionPassword'),
        authenticated: sessionStorage.getItem('sessionAuthenticated')
    });

    const [watchlist, setWatchlist] = useState([]);


    useEffect(() => {
        getWatchlist()
    }, [])


    function getWatchlist() {
        console.log(`get watchlist running`);

        axios.post(`/api/users/watchlist/id/${Cookies.get("email")}/${Cookies.get("pass")}`).then((res) => {
            if (res) {
                setWatchlist(res.data)
                console.log(`user.name ${Cookies.get("name")}`)
                console.log(` This is the res.data: ${JSON.stringify(res.data)}`)
            }
        }).catch((err) => {
            console.log(err);
        })


        console.log(`run added ${run}`);
    }





    function addToList() {
        console.log(ticker);
        axios.post(`/api/users/watchlist/add/${ticker}/${Cookies.get("email")}/${Cookies.get("pass")}`).then((res) => {
            console.log(res)
        }).then(getWatchlist())
            .catch((err) => {
                console.log(err)
            })


        setRun(run + 1);


    }

    function handleSubmit(props) {
        props.preventDefault();
        console.log(`${ticker} ${Cookies.get("email")} ${Cookies.get("pass")}`)

        addToList();
    }






    return (




        <div>
            <Navbar />

            <div className="row" style={{ justifyItems: 'center' }}>
                <div class="card col-6" >
                    <h3 class="card-title">Watchlist</h3>
                    <div class="card-body">
                        <ul className="col-7-md list-group list-group-flush">
                            {watchlist.map((element) => { //############# this is where its mapped##################
                                console.log("setTickerList is running")
                                return <a class="list-group-item" onClick={() => {
                                    console.log("selectStock: ");
                                    Cookies.set('currentStock', `${element.Ticker.toUpperCase()}`, { sameSite: 'strict', expires: 1 })
                                    console.log("current stock: " + JSON.stringify(Cookies.get("currentStock")));
                                    window.location.href = '/home'

                                }}>
                                    <div>
                                        {element.Ticker.toUpperCase()}
                                    </div>

                                </a>
                            })}
                        </ul>

                    </div>
                </div>
            </div>


            <div className="card">
                <h3 className="card-title text-center">Add To Watchlist</h3>
                <div className="form" onSubmit={evt => handleSubmit(evt)}>
                    <div className="form-group">
                        <div className="form-group">
                            <input
                                type="text"
                                name="ticker"
                                value={ticker.value}
                                placeholder={"Enter ticker here"}
                                onChange={(evt) => { setTicker(evt.target.value) }} />
                        </div>
                        <button className="btn btn-light "
                            type="submit"
                            onClick={addToList}
                            style={{ margin: '25px' }}>
                            Add Stock
                            </button>
                    </div>
                </div>
            </div>
        </div>


    )


} export default Watchlist; 

Here's what it looks like Website

Upvotes: 0

Views: 126

Answers (1)

Kanti vekariya
Kanti vekariya

Reputation: 697

try this one

function getWatchlist() {
        console.log(`get watchlist running`);

        axios.post(`/api/users/watchlist/id/${Cookies.get("email")}/${Cookies.get("pass")}`).then((res) => {
            if (res) {
                setWatchlist(watchList => [...watchList, res.data]);
                console.log(`user.name ${Cookies.get("name")}`)
                console.log(` This is the res.data: ${JSON.stringify(res.data)}`)
            }
        }).catch((err) => {
            console.log(err);
        })


        console.log(`run added ${run}`);
    }

Upvotes: 1

Related Questions