RoffyBC
RoffyBC

Reputation: 189

setState to the localstorage.getItem in ReactJS

I want to set 'username' in the state to the localstorage.getItem,but the problem is it is not working,Any suggestions?

class ToDoApp extends Component {
state = {
    username:'',
    inputValue: '',
    todos: [],
    currentPage: 1,
    pageCount: 1,
    itemsPerPage: 10,
};

Function with posts item to the data:

addItem = () => {
    let {todos} = this.state
    let userName = localStorage.getItem('username')
    console.log(userName)
    if (this.inpRef.current.value === '') {
        return alert('We dont do that here....')
    } else {
        axios
            .post(`http://localhost:8080/add`, {
                username:userName,
                todo: this.inpRef.current.value,
                checked: false,
            })
            .then((res) => {
                this.setState({
                    todos:[...todos,{username:res.data.username,todo:res.data.todo,_id:res.data._id,checked:false}]
                })
                console.log(todos)
            })
            .catch((err) => {
                console.log("err", err);
            });
        this.setPageCount()
    }
    this.inpRef.current.value = ''
    console.log('--------this.state.todos', this.state.todos);
}

Upvotes: 2

Views: 471

Answers (1)

Red Baron
Red Baron

Reputation: 7642

setState is async

can you try this:

this.setState({ 
    todos:[...todos { username:res.data.username,todo:res.data.todo,_id:res.data._id,checked:false}]
}, console.log(this.state.todos))

setState has a callback as a second arg so you can check if it's actually been set here

Upvotes: 2

Related Questions