Search code examples
reactjssession-storage

Get ID element from url and store it in a session array every time page loads


In reactjs, I am trying to store the id to session storage array which comes from URL, for example, http://localhost:3000/#/carnivallist/171 what's the solution to store all the ids?

I can only store one id. when the page refreshes the id is getting replaced on the session storage.

componentDidMount() {


        if(this.props.params.id) {
            let pro_id=[this.props.params.id];
            console.log(pro_id);

            console.log("otem");
            let items=sessionStorage.getItem("carnival_dones");
            console.log(items);
            if(items!=""){
                this.setState({ carnival_done: [...this.state.carnival_done,{carnival_done:pro_id}]});

            }else{
                this.setState({carnival_done:pro_id});
            }

        }
    }

I expect to get all ids in an array but the session storage stores only the last value get saved. and the value not accessible through the session get method


Solution

  • The problem was I was using the componentDidMount method instead of using componentWillMount so I found a solution changing the hook

     componentWillMount() {
        if(this.props.params.id) {
            let pro_id=[this.props.params.id];
            console.log(pro_id);
    
            console.log("otem");
            let items=sessionStorage.getItem("carnival_dones");
            console.log(items);
            if(items!=null){
                this.setState({carnival_done:[...this.state.carnival_done,[items,pro_id]]});
                //this.setState({ carnival_done: [...this.state.carnival_done,pro_id]});
                console.log(this.state.carnival_done);
            }else{
                this.setState({carnival_done:[pro_id]});
            }
    
    
        }
    
    }
    

    Thank you so much for your support