reactjs data mapping, get data from server

1.9k Views Asked by At

I'm new reactjs I'm trying to save data that I got from server like object(array) but I can't.

demo

at render() function, what should I do to save data, I don't wanna display, just save to users (array) or something? I think that I should use "map" but I don't know how to do. Next, I wanna save users to model.data like this. help me.

demo2

2

There are 2 best solutions below

2
oemera On

Since you just started using react, try using React Hooks instead of class style components. It's the recommended way.

If you just want to store the data without displaying anything you need somekind of a encapsulated/shared state. For example redux or context can help you with that. Since context is in-built and easier to use, here is an example:

First create a context

users-context.js

import React from "react";

export const UsersContext= React.createContext();

Now create a custom hook to store your state.

useUsers.js

import React, {useState, useEffect} from "react";
export const useUsers = () => {
  const [users, setUsers] = useState([]);

  const getUsers = () =>{
    //your fetch
  }

  useEffect(()=>{ //equivalent to componentDidMount
    getUsers();
  }, [])

  return {users, setUsers}
}

Then provide the context so every component in your app has access to that context.

App.jsx

import {UsersContext} from "./UsersContext";

const App = () => {

const contextValue = useUsers();

return (
    <div className={'App'}>
      <UsersContext.Provider value={contextValue}>
        <Main/>
      </UsersContext.Provider>
    </div>
   );
 };

 export default App;

If you want to use the state in a component, e.g. a profile page do this:

profile-page.jsx

import React, {useContext} from "react";
import {UsersContext} from "./UsersContext";

const ProfilePage = () => {
const {users} = useContext(UsersContext);

// now you can use it like
console.log(users)

return (...) 
}
0
Simpa407 On
import { UsersContext } from './Components/usersData/users-context';
const getUsers = () => {
  const {users} = UsersContext(UsersContext);
  console.log(users);
  return users;
}
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
            data:[]
        }
    data.push(getUsers);`
    }
  }