-1

I am getting back-end data by using axios.get(), but the array of objects is not populating the state.

It's giving me following in the console.

Outside Effect {success: true, message: 'All Categories List', category: Array(2)} [] Outside Effect[object Object],[object Object]

Back-end code is also given.

Front-end

const [categories,setCategories] =useState([])

const getAllCategory = async () => {
    try {
      const  {data}  = await axios.get("/api/v1/category/get-category");
      if (data.success) {
        console.log(data)
        setCategories(data.category);
        console.log(categories)
      }
    } catch (error) {
      console.log(error);
      toast.error("Something went wrong in getting category");
    }
  };

useEffect(() => {
    getAllCategory();
  }, []);
console.log("Outside Effect", categories)

Rendering

  <table className="table">
    <thead>
      <tr>
        <th scope="col">Name</th>
        <th scope="col">Actions</th>
      </tr>
    </thead>
    <tbody>
      
        {categories.map((c)=>{
          <tr>
          <td key={c._id}>{c.name}</td>
          </tr>
        })}
      
    </tbody>
  </table>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Nothing ever modifies `categories`, so it's not clear how or why that would ever be anything other than an empty array. And nothing here logs "Outside Effect" at all to the console. Can you elaborate on specifically what you're trying to describe? Ideally, please include a runnable [mcve] which demonstrates the problem. (Using hard-coded sample data for demo purposes if necessary.) – David May 12 '23 at 14:10
  • you're should be using ```setCategories``` and not ```setCart``` – David Grosh May 12 '23 at 14:11
  • I need to populate the category array with the backend data. that is what we can do using setCategory(data.ategory). I have also added backend code if you need to take a look – Aritra Mukherjee May 12 '23 at 14:31
  • @AritraMukherjee: Regarding the update... What specifically is outputting this "Outside Effect" value? That string doesn't exist in the code shown. Is that string in your data? What is the exact problem you're asking about? If you're asking why "[object Object]" is being printed then that implies that somewhere the code is interpreting an object as a string. Potentially wherever that "Outside Effect" string is being added. But the code shown doesn't do that anywhere. Please clarify specifically what you're asking. – David May 12 '23 at 14:43
  • I am using setCatagories() by mistake it was written setCart(). But still its not working – Aritra Mukherjee May 12 '23 at 14:43
  • @AritraMukherjee: "It's not working" tells us exactly ***nothing*** about the problem you're observing, the specific behavior you are expecting, why specifically you are expecting that behavior, etc. Please don't randomly change the code and repeat "it's not working" and instead take some time to ensure you've provided a [mcve] and clearly indicate the specific problem you are trying to solve. – David May 12 '23 at 14:45
  • sorry for that. now you can check – Aritra Mukherjee May 12 '23 at 14:45
  • @AritraMukherjee: Already voted to close for another reason, but it looks like this is now a duplicate of [this question](https://stackoverflow.com/q/69474477/328193). You're trying to use an object as a string, and "[object Object]" is the default string representation for an object. Use this instead: `console.log("Outside Effect", categories)` – David May 12 '23 at 14:47
  • yes. catagories is populating. but I have to show the data in a table format. its not rendering in the browser. why? How Can I do that? – Aritra Mukherjee May 12 '23 at 14:59
  • @AritraMukherjee: What's "not rendering in the browser"? There's no "table format" in the code shown. What specifically are you referring to? What does it have to do with the question being asked? Again, ***please be clear and specific*** about the problem you are observing and the question you are asking. If what you're asking now is a different question, please ask it separately. Don't just keep making changes and keep repeating "it's not working" in the hopes that, piece by piece, this community will write your whole application for you. – David May 12 '23 at 15:01
  • 1
    Based on the console logs it seems clear to me the `categories` state was updated/populated. What is the problem? You can't console log state right after enqueueing a state update as React state isn't guaranteed to be immediately synchronously updated. In fact, it's just about a guarantee ***not*** to since state is declared const and won't change in the closure of the `getAllCategory` function scope. – Drew Reese May 12 '23 at 15:03
  • sorry to offend you but I have to access the category array and map it into table format. firstly I was thinking that array is not populating. but thanks to you. its populating. then it should render in browser right. I am not expecting the community to write code for me. but its somewhere I stuck. thats why I am here. I am adding the return part also – Aritra Mukherjee May 12 '23 at 15:05
  • @AritraMukherjee: *"I have to access the category array and map it into table format."* - You are encouraged to make an attempt to write your code. If you encounter a specific technical problem during that attempt, such as an error or unexpected result, we can help with that. Please provide specific information about that attempt and what didn't work as expected. To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David May 12 '23 at 15:06
  • 1
    @AritraMukherjee: If you're encountering a new, separate issue then please create a new, separate question. This one is already a mess, adding further confusion won't improve it. – David May 12 '23 at 15:07
  • @DrewReese yes categories is populated but while rendering in browser using map function it not showing anything. – Aritra Mukherjee May 12 '23 at 15:17
  • 1
    You are mapping the `categories` array, that's good. ***What*** are you mapping though? Does each `categories` array element have `_id` and `name` properties? You keep editing the post and moving the goal posts. Changing the post ***after*** answers have been provided invalidates existing answers. This post has already been closed as a duplicate from the an earlier version of your post. If you have a new issue it's better to create a new SO post for the new specific issue. – Drew Reese May 12 '23 at 15:20
  • @DanMork its rendering – Aritra Mukherjee May 12 '23 at 15:23
  • @DrewReese yes each categories array have element _id and name – Aritra Mukherjee May 12 '23 at 15:26
  • The map callback needs to return a value. You are mapping an array from one set of values to an array of *different* values, e.g. JSX. The current code doesn't return any mapped value so you have an array of undefined values. – Drew Reese May 12 '23 at 15:29
  • @DrewReese can you explain how – Aritra Mukherjee May 12 '23 at 15:32
  • @AritraMukherjee, great! Looks like Drew helped you find the rendering issue. I updated the Gist I shared to show what Drew is saying about returning content from your `.map` function. – Dan Mork May 12 '23 at 15:34
  • This [post](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) should help clear up confusion regarding the use of javascript arrow functions and returning values. – Drew Reese May 12 '23 at 15:34
  • @DanMork json.stringify renders the object. but when i am trying to access the object with the help of map() its not rendering – Aritra Mukherjee May 12 '23 at 15:43
  • If you are having trouble rendering the array from state, then please create a new post specific to that issue. If you do, please ensure it includes a complete [mcve] that includes an example of the data you are trying to render. Feel free to ping me here in a comment with a link if you like, and I can take a look when available. – Drew Reese May 12 '23 at 15:52

1 Answers1

0

other then the typo, console.log(categories) just below the setState will not show the updated categories as setState is asynchronous process. you can add one more use effect for that ->

useEffect(() => {
    console.log(categories)
  }, [categories]);
theNaukiMatic
  • 61
  • 1
  • 3