• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 React 게시판 redux-toolkit ajax통신하기 질문입니다!

redux-toolkit ajax통신하기 질문입니다!

6 글 보임 - 1 에서 6 까지 (총 6 중에서)
  • 글쓴이
  • #96613

    신혜원
    참가자
    (shop.js)
    import { changeItem } from "../../store";
    import { useDispatch } from "react-redux";
    
      const [shopItems, setShopItems] = useState();
      let dispatch = useDispatch();
    
      useEffect(() => {
        axios
          .get(
            "https://raw.githubusercontent.com/mimkong/meongmeongdata/master/data.json"
          )
          .then((result) => {
            setShopItems(result.data);
            dispatch(changeItem(result.data));
          })
          .catch(() => {
            console.log("json 데이터를 불러오는데 실패했습니다.");
          });
      }, []);
    
    (store.js)
    import { configureStore, createSlice } from "@reduxjs/toolkit";
    const item = createSlice({
      name: "item",
      initialState: "",
      reducers: {
        changeItem(state) {
          return state;
        },
      },
    });
    export default configureStore({
      reducer: { item: item.reducer },
    });
    export const { changeItem } = item.actions;
    
    
    (Detail.js)
    import { useSelector } from "react-redux";
    function Detail() {
      let a = useSelector((state) => {
        return state;
      });
      console.log(a);
      return (
        <>
          <div>detail페이지입니다.</div>
        </>
      );
    }
    
    
    (store.js)에서 initialState에 ajax로 가져온 json 데이터를 넣고 싶습니다.
    그래서 state를 변경하기 위해 dispatch를 사용했는데 console.log(a) 에 데이터가 뜨지 않습니다 ㅠㅠ
    도와주세요....
    #96625

    codingapple
    키 마스터
    state 도착전에 console.log가 먼저 실행되나봅니다 a는 html에 넣어봅시다
    #96631

    신혜원
    참가자
    (Detail.js)
    import { useSelector } from "react-redux";
    function Detail() {
      let a = useSelector((state) => {
        return state;
      });
      return (
        <>
          <div>detail페이지입니다.</div>
          <p>{a.item}</p>
        </>
      );
    }
    export default Detail;
    화면 캡처 2023-09-02 131925화면 캡처 2023-09-02 132137
    
    a를 html에 넣어보았는데 state변경이 잘 되지 않는 것 같습니다...
    콘솔창에 이런 경고창이 뜨는데 혹시 이것때문일까요?
    #96658

    codingapple
    키 마스터
    shop.js 페이지 방문하면 useEffect 동작되고있나 확인해봅시다
    #96674

    신혜원
    참가자
    shop.js에서는 useEffect 잘 동작하여 카테고리 아이템에 잘 들어갑니다!
    
    (shop.js)
    
    import Category from "./Category";
    import ProductList from "./ProductList";
    import { useState, useEffect } from "react";
    import axios from "axios";
    import { changeItem } from "../../store";
    import { useDispatch } from "react-redux";
    function Shop({}) {
      const categoriesData = [
        { name: "ALL", categories: null },
        { name: "LIVING", categories: "living" },
        { name: "WALKING", categories: "walking" },
        { name: "CLEAN", categories: "clean" },
        { name: "FOOD", categories: "food" },
      ];
      let [selectedCategory, setSelectedCategory] = useState(null);
      let handleCategorySelect = (type) => {
        setSelectedCategory(type);
      };
      let [shopItems, setShopItems] = useState();
      let dispatch = useDispatch();
      useEffect(() => {
        axios
          .get(
            "https://raw.githubusercontent.com/mimkong/meongmeongdata/master/data.json"
          )
          .then((result) => {
            setShopItems(result.data);
            dispatch(changeItem(result.data));
          })
          .catch(() => {
            console.log("json 데이터를 불러오는데 실패했습니다.");
          });
      }, []);
      return (
        <>
          <h1>SHOP</h1>
          <Category
            categories={categoriesData}
            selectedCategory={selectedCategory}
            onSelectCategory={handleCategorySelect}
          />
          <ProductList
            shopItems={
              selectedCategory === null
                ? shopItems
                : shopItems.filter((item) => item.type === selectedCategory)
            }
          />
        </>
      );
    }
    export default Shop;
    혹시몰라 shop.js 전체코드 올립니다!!
    #96702

    신혜원
    참가자
    흐아 useEffect를 App.js에 했더니 해결했습니다... 내일 Node.js, MongoDB 강의 하루만에 완강 해야겠네요 ㅠㅠ
6 글 보임 - 1 에서 6 까지 (총 6 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠