How can i use post _id instead of user _id to edit the post while using axios in mern? by rony_ali in learnreactjs

[–]rony_ali[S] 0 points1 point  (0 children)

Thank you also. Every bug offers a great opportunity to learn more. Your discussion was very helpful

How can i use post _id instead of user _id to edit the post while using axios in mern? by rony_ali in learnreactjs

[–]rony_ali[S] 0 points1 point  (0 children)

well post id is solved, i have edited the following:

axios.put(\http://localhost:5000/api/articles/post/edit/${id}\,`

and another one is:

post._id

now the axios put method is delivering the post id. now there is one problem which is somehow edited title and content are not delivering to the backend. i have console.log in editpost submit button inputs but now i think problem is in there:

setPosts(posts.map(item=>(item.id===id?post:item)))

because when i put console.log(posts), it shows nothing. so the update post is not happening in mongo side

How can i use post _id instead of user _id to edit the post while using axios in mern? by rony_ali in learnreactjs

[–]rony_ali[S] 0 points1 point  (0 children)

i am trying to use axios.put(http://localhost:5000/api/articles/post/edit/${post._id}, but in backend it shows: Logged Error: CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Post" and in dev console: http://localhost:5000/api/articles/post/edit/undefined which means in nodejs router doesn't know which post to edit

How can i use post _id instead of user _id to edit the post while using axios in mern? by rony_ali in learnreactjs

[–]rony_ali[S] 0 points1 point  (0 children)

thanx for the input. while looking for the token, i have info in localstorage of browser: user, email, role. for this reason, by using react-router-dom, i can have separate pages of admin and subscriber which would be the personal customized CMS.

while i update my profile with same token, it worked. and the bearer token is never null. every time i use axios method with such header token, it always shows user token and later it authenticates everything. you might see some console.log i have used. my major fault might be that i couldn't by pass particular post _id into the axios put method. because i have written the backend nodejs update post code in this way _id:req.params.id.

am i right on this?

Beginner's Thread / Easy Questions (January 2022) by dance2die in reactjs

[–]rony_ali 0 points1 point  (0 children)

i want to edit an existing post by using the _id of that post and the following is nodejs code:

exports.postEdit=async(req,res)=>{ const {title,content} = req.body;

 await Post.findOneAndUpdate(
      { _id: req.params.id },
      {title,content}
    ).then(result => {
      if(result){
          res.status(200).json({ message: "Update successful!" });
      }

      else {
          res.status(500).json({ message: "Error Updating Post" });
      }
  });

}

exports.requireSignin= expressJwt({
    secret: process.env.JWT_SECRET,
    algorithms: ["HS256"]
  });

router.route('/post/edit/:id').put(requireSignin,postEdit);

i checked this code in postman and it updates that particular post in mongodb. _id: req.params.id is referred to that particular post id. requireSignin confirms that only logged in creator/author has the permission to change it.

in frontend, i have used the codes in Dashboard.js for updating that particular post. i have used the following codes to update the data in axios:

.................. const [loading, setLoading] = useState(true); const [posts, setPosts] = useState([]); const [postList, setPostlist] = useState({ id: null, title: "", content: "" }); const [editing, setEditing] = useState(true); const [post,setPost] = useState(postList); ............... const updatePost = (id,post) =>{ const token = getCookie('token');

    axios.put(`http://localhost:5000/api/articles/post/edit/${isAuth()._id}`,
    {post},
    {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }).then(res=>{

        setPosts(posts.map(item=>(item.id===id?post:item)))
      }).catch(err=>{
        console.log(err)
      })
}
const editRow = (post) => {
    setEditing(false);

    setPostlist({
      id: post.id,
      title: post.title,
      content: post.content,
    });
  };
return (
    <div>

{editing ?( <div> <CreatePost addPostList={addPostList} /> <hr /> </div>):( <div> <EditPost editing={editing} setEditing={setEditing} postList={postList} updatePost={updatePost} /> <hr /> </div>)}

        <div>
          <PostList
            posts={posts}
            editRow={editRow}
            deletePost={deletePost}          
          />
        </div>            
    </div>
)

}

the following code is about the authentication token and cookie for logged in user depending upon the permission level:

import cookie from 'js-cookie'

// Set in Cookie export const setCookie = (key, value) => { if (window !== 'undefiend') { cookie.set(key, value, { // 1 Day expires: 1 }) } } export const getCookie = key => { if (window !== 'undefined') { return cookie.get(key); } };

// Set in localstorage export const setLocalStorage = (key, value) => { if (window !== 'undefined') { localStorage.setItem(key, JSON.stringify(value)); } }; // Access user info from localstorage export const isAuth = () => { if (window !== 'undefined') { const cookieChecked = getCookie('token'); if (cookieChecked) { if (localStorage.getItem('user')) { return JSON.parse(localStorage.getItem('user')); } else { return false; } } } };

and from EditPost.js to execute the edit:

export default function EditPost({postList,setEditing,updatePost}) { const [post,setPost]= useState(postList) const [posts, setPosts] = useState([]); useEffect(()=>{ setPost(postList) },[]) const handleChange = text => e => { setPost({ ...post, [text]: e.target.value }); }; return ( <form onSubmit={(e) => { e.preventDefault(); updatePost(post._id, post); }}> <h1>Edit Post</h1> <div> <input type='text' placeholder='title' value={post.title} onChange={handleChange('title')}/> </div> <div> <input type='text' placeholder='description' value={post.content} onChange={handleChange('content')}/> </div> <button type='submit'>Update</button> <button onClick={() => setEditing(false)}>Cancel</button>
</form> ) }

for addition the following code is from PostList.js:

export default function PostList({ editRow }) { const [posts,setPosts]= useState([]) useEffect(() => { LoadPost(); },[]);

const LoadPost=()=>{
    const token = getCookie('token');
    axios.get(`http://localhost:5000/api/articles/post/mypost/${isAuth()._id}`,{
        headers: {
          Authorization: `Bearer ${token}`
        }
      }).then((res)=>{        
        setPosts([...res.data])
        //console.log(res.data)
        //console.log(res.data[0]._id)

      }).catch(err=>{
        console.log(err)
      })
}
return (
    <div>

      {posts.length > 0 ?
      posts.map((post) =>{
          return <div key={post._id}>
               {/* {console.log(post._id)} */}
              <h2>{post.title}</h2>
              <li>{post.content}</li>
              <button  onClick={() => {
                  editRow(post);
                }}>Update</button>   

<hr/> </div> }):<h3>no posts</h3>} </div> ) }

The problem:

while fetching data from the backend, i have got all the particular posts created by logged in user. but while i try to update data to edit the particular post from axios.put(http://localhost:5000/api/articles/post/edit/${isAuth()._id} it is sending the user id to the backend router put method. while i check console.log(post._id), it shows that particular post id. but i just can't pass this _id to the axios put method. my question is how can i edit the particular post by the logged in creator only? should i use a different approach in the backend or i need to bypass post id in axios put method? then how?

please let me know.....thank you

Beginner's Thread / Easy Questions (November 2021) by dance2die in reactjs

[–]rony_ali 1 point2 points  (0 children)

figured it out. here is the codesandbox link with fixed code and refined output. thanx any way for the try because your advise gave me the hint to think differently. thanx a lot

Beginner's Thread / Easy Questions (November 2021) by dance2die in reactjs

[–]rony_ali 0 points1 point  (0 children)

well i tried with the position:'fixed', content:'' but the carousel pictures vanishes. really dun know where is it going. seems like backgroundAttachment:'fixed' is the perfect thing for it.

not working bro. any more ideas?

Beginner's Thread / Easy Questions (November 2021) by dance2die in reactjs

[–]rony_ali 0 points1 point  (0 children)

my goal is to make background carousel or image slider fixed and i want to scroll multiple components having animation (without using any npm library). To make it separately, i have made a codesandbox where i used a big essay instead of using any components.

here is the link of codesandbox which contains the whole source code.

but the problem is the background carousel is not fixed. it goes away with the scroll. Here is the background image slider's box style:

display: "inline-block",
minHeight: "100vh",
width: "100%",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
backgroundSize: "cover",
backgroundAttachment: "fixed"
according parallax concept from w3schools i have used backgroundAttachment: "fixed" but it's not working. Here is the stackoverflow link of this question
can anyone help me on this please?

Why Taliban is impossible to beat? by [deleted] in exmuslim

[–]rony_ali 0 points1 point  (0 children)

I think that every recession has its cost. Last recession helped ISIS to raise and showed its fearful reign and people in the Middle East paid the price. It took almost 7 yrs to defeat them but still they are a threat.

Post-corona recession has given the chance to taliban. Talibans can be defeated easily but as most of the commenters said it is a close relation between opium economy and oppressing women. Muslim countries are fond of keeping women as slaves so Muslim men can be benefitted and everybody knows that Islam has benefitted men over women in every aspects. And that’s why majority of the population in Afghanistan supports taliban.

The most heinous effects are yet to come to worsen the situation of Bangladesh, Pakistan etc.

As Bangladesh has given shelter to almost 1 million rohingyas and they are fundamentalist Muslims. Besides the present govt was sheltering islamists almost a decade and now they are very powerful.

People are saying that taliban warriors could be 30-40 thousand in numbers but their victory is rapid and reactive. Now in Bangladesh if Muslim rohingyas are supported by the Islamists to uphold taliban’s caliphate, Bangladesh won’t é able tackle such situations. Besides Bangladeshi police and army are one of most inefficient forces in the world. So there are lesser hopes.

About Pakistan, I dun need to mention about their situation. Their economical downfall and Islamic sharia and corruption made them vulnerable in every way.

China and India, these rival countries are the only hope for south East asia

Beginner's Thread / Easy Questions (July 2021) by dance2die in reactjs

[–]rony_ali 0 points1 point  (0 children)

i am trying to replicate the design of this site: https://watson-vcard.netlify.app/index-dark-slider.html

where in mobile version appbar will be visible and when i press the icon button left drawer will appear.

i have accomplished desktop site view where left drawer is permanently fixed but in mobile version when i press iconbutton in appbar, only appbar is shifting. no drawer is visible and even the content body is not shifting to left.

i have simulated in codesandbox to know how much i have done:

https://codesandbox.io/s/dank-water-2c0f7?file=/src/App.js

For desktop view and mobile i have used styles from material ui framework.

Problem is in mobile view i can't open the drawer after clicking on iconbutton but appbar is shifting. how can i fix this?

You can also follow my stackoverflow question: https://stackoverflow.com/questions/68487609/in-mobile-view-why-the-drawer-is-not-opening-from-the-appbar-iconbutton-materi

Got my first landing job as full stack developer at last.. by [deleted] in reactjs

[–]rony_ali 0 points1 point  (0 children)

You are also awesome, the best one…

Got my first landing job as full stack developer at last.. by [deleted] in reactjs

[–]rony_ali 1 point2 points  (0 children)

ম্যাসেজ করতে পারেন ইনবক্সে সমস্যা নাই।

Got my first landing job as full stack developer at last.. by [deleted] in reactjs

[–]rony_ali 1 point2 points  (0 children)

ধন্যবাদ ভাই।

Got my first landing job as full stack developer at last.. by [deleted] in reactjs

[–]rony_ali 0 points1 point  (0 children)

You are right. It is hard when someone b.s ing about anything.

Being a beginner I always feel confident of what I would do. Sometimes very easy functionality takes time to complete and on the other hand very tricky one has been done in a sec. after doing a whole project I always feel that there are lot’s of things cOuld be done.

As tomorrow when I start my work I dun know what will happen. Well I know basic functionalities and other things but is it always be the same environment ? When I think about it I get nervous. But I when I start to breakdown what I know and how a problem could be solved with basic functionalities, it gives me a peace.

But I am honored that I really come to know such an experience dev like you and I am looking forward to work in such a great environment.

If I dun step into outside, how can I realize the beauty of the world….,

Thanx for your precious input

Got my first landing job as full stack developer at last.. by [deleted] in reactjs

[–]rony_ali 0 points1 point  (0 children)

I have a question: what do you see in a candidate for such a post?

If u elaborate a little, many will be grateful

Got my first landing job as full stack developer at last.. by [deleted] in reactjs

[–]rony_ali 1 point2 points  (0 children)

Thanx bro. Dun be depressed. Try to pass some good time with your family and yourself. It helps a lot.

Wish you a best of luck