[SOLVED]-HOW TO TRIGGER AN EFFECT AFTER AN EVENT IN REACT-REACTJS

HOW TO TRIGGER AN EFFECT AFTER AN EVENT IN REACT-REACTJS

post.js

export default function post(props) {
  const user = usecontext(usercontext);

  const [content, setcontent] = usestate('')
  const [title, settitle] = usestate('')
  const [comments, setcomments] = usestate([])

  const onnewcomment = usecallback((text) => {
    // i'm not sure about your comment structure on server. 
    // so here you need to create an object that your `comments` component 
    // will be able to display and then do `setcomments(comments.concat(comment))` down below
    const comment = { 
      comment: text,
      users_id: user.users_id,
      posts_id: props.location.state.id,
    };
    async function sendcomment(url) {
      try {
        const res = await fetch(url, {
          method: 'post',
          body: json.stringify(comment),
          headers: {
            accept: 'application/json',
            'content-type': 'application/json',
            'accept-language': 'en-us',
          },
        });
        return res;
      } catch (e) {
        console.log(e);
      }
    }
    const res = await sendcomment(comment_submit_url);
    if (res.ok) {
      setcomments(comments.concat(comment));
    }
  }, [comments]);

  useeffect(() => {
    const unique_post_url = [post_url, props.location.state.id].join('/');

    const fetchpost = async () => {
      const result = await fetch(unique_post_url);
      const { content, comments, title } = await result.json();
      setcontent(content);
      setcomments(comments);
      settitle(title);
    };
    fetchpost();
  }, [props.location.state.id]);

  return (
    <div>
      <container>
        <typography
          variant="h4"
          color="textprimary"
          style={{textdecoration: 'underline'}}>
          {title}
        </typography>
        <markdown>{content}</markdown>
        {content.length !== 0 && (
          <div>
            <typography variant="h4">comments</typography>
            <sendcomment user={user} onnewcomment={onnewcomment} />
            <comments user={user} comments={comments} />
          </div>
        )}
      </container>
    </div>
  );
}

sendcomment.js

export default function sendcomment(props) {
  const [text, settext] = usestate('');
  const handlesubmit = usecallback(() => {
    // skip empty comments
    if (comment.value === '') {
      return;
    }
    if(props.onnewcomment) {
      props.onnewcomment(text);
      settext('');
    }
  }, [props.onnewcomment, text]);

  return (
    <grid container justify="space-evenly" direction="row" alignitems="center">
      <grid item xs={8}>
        <textfield
          id="comment"
          onchange={settext}
          fullwidth
          multiline
          rowsmax="10"
          margin="normal"
          variant="filled"
        />
      </grid>
      <grid item xs={3}>
        <button variant="contained" color="primary" onclick={handlesubmit}>
          submit
        </button>
      </grid>
    </grid>
  );
}

comments.js

export default function comments(props) {
  const commentlist = props.comments.map(comment => (
    <listitem key={comment.id} alignitems="flex-start">
      <listitemavatar>
        <avatar alt={comment.users.name} src={comment.users.picture} />
      </listitemavatar>
      <listitemtext
        primary={`${comment.users.name} - ${timeago(comment.created_at)}`}
        secondary={comment.comment}></listitemtext>
      <divider />
    </listitem>
  ));

  return <list>{commentlist}</list>;
}

upd: changed some code to display content and title in post.js

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments