Reputation: 62
class PostIndex extends Component {
//define state
const [posts, setPosts] = useState([]);
//useEffect hook
useEffect(() => {
//panggil method "fetchData"
fectData();
}, []);
//function "fetchData"
const fectData = async () => {
//fetching
const response = await axios.get('http://localhost:3000/api/posts');
//get response data
const data = await response.data.data;
//assign response data to state "posts"
setPosts(data);
}
}
export default PostIndex;
please help me, i new learning at react js. i was about make class name PostIndex, so i change from function PostIndex() to class PostIndex extends Component. and get error from this line const [posts, setPosts] = useState([]); could you help me? please. thanks
Upvotes: 0
Views: 1446
Reputation: 119
You can't use React Hooks such as useState in class component. It only works in functional component. If you want to use state in class component, please follow as:
class PostIndex extends React.Component {
state = {posts: []}; // define state
.....
this.setState({
posts: ['a', 'b']
}); // set state
.....
let temp = this.state.posts; // use state
.....
I hope this will help you. Thanks.
Upvotes: 1
Reputation: 107
You can't use hooks in the class components, check docs rather use functional component:
const PostIndex = () => {
const [posts, setPosts] = useState([]);
// rest of your code....
}
export default PostIndex;
Upvotes: 1
Reputation: 143
You cant use react class components with react hooks.
So the right solution will be something like this:
const PostIndex = () => {
//define state
const [posts, setPosts] = useState([]);
//useEffect hook
useEffect(() => {
//panggil method "fetchData"
fectData();
}, []);
//function "fetchData"
const fectData = async () => {
//fetching
const response = await axios.get('http://localhost:3000/api/posts');
//get response data
const data = await response.data.data;
//assign response data to state "posts"
setPosts(data);
}
return your markup
}
Upvotes: 1