Home > Mobile >  Can I change the state in reactjs without reloading the page
Can I change the state in reactjs without reloading the page

Time:03-14

Can I change the state of a component in reactjs without reloading the page? I have a react app with nodejs where users can make comment on a post. I don't want the entire page to reload each time a user makes a comment. This I have achieved but I noticed that after the Post api call for making a post, the new states will not reflect until a page reload. Here is my code:

const [commentdescription, setCommentDescription] = useState('');

const handleComment = async ()=>{
 
const newComment = {
    author: user.userId,
    role: user.role,
    commentdescription,
};

try{
     setIsLoading(true)
    await axiosPrivate.post("/posts/"  path   "/comment", newComment, { withCredentials: true,
        headers:{authorization: `Bearer ${auth}`}
        });
        
       setIsLoading(false)
       setCommentDescription('')
}catch(err){
    console.log(err)
}
};

This is how I connected the comment state with a button that calls the api:

<textarea className='comment-wrapper' type='text' placeholder='Share your comment'
            onChange={(e) => setCommentDescription(e.target.value)}></textarea>
        <button className={isLoading? 'comment-btn-no-cursor comment-btn' : 'comment-btn'}onClick={handleComment}>Post Comment</button>

I wanted setCommentDescription to be set back to empty string but it does not reflect after the comment has been made. It only reflects once the page refreshes. Though the new comment made actually reflects on the page. The major reason I want to get this implemented is this: when a user makes a comment on the post, the comment reflects on the post for sure after successful to the api using axios, however, the text contents of the user remains inside the textarea box until the page is refreshed which will now make the textarea box to pick the default state which is an empty string. This doesn't look good at all. I would like the textarea box to reflect the state after the successful api call without reloading the entire page. It makes no sense for the entire page to reload each time a user makes a comment. This same issue is happening with replies to comments.

How can I get the new state to work without refreshing the entire page?

CodePudding user response:

  1. If you dont want to reload a page on state change, then instead of useState() use useRef() for useRef() store and update the references to data variables without reloading a page on data changes

  2. Back to your new problem, for the empty string for the comment make sure on your UI if you're using <input tag value to equal to commentdescription

But if you're using textarea make sure to enclose it with commentdescription

as <textarea>{commentdescription}</textarea>

CodePudding user response:

Edit: Ok, with the updated code I see you're missing: value={commentdescription} on the <textarea> - you always need both onChange and value for a two-way binding

Original comment:

Your code looks good as it's shown here.

How did you connect your text input with commentdescription? Do you have a binding in value and onChange?

Any output in the browser console?

  • Related