0

概要

現在、TypeScript+React+Redux+Go+gRPCを用いた個人開発を行っています。
そこで、gRPCで受け取った3次元配列のレスポンスをReducerに記述したいのですが、そこで今悩んでいます。
具体的には3次元配列の値をinitialStateにコピーする方法がわかりません。通常の一次元ならば記述できますので、配列を崩してReducerを複数作ることも考えたのですが、それはどうなのかと思い今悩んでいます。
自分なりに色々工夫してみましたが、解決せず。
どなたか解決方法のご教授お願い致します。

該当するコード

// Protocol Buffers

message ClearingHistoryRequest {
    string token = 1;
}
message ClearingHistoryResponse {
    bool status = 1;
    enums.StatusCodes status_code = 2;
    repeated Clearing ClearingHistory = 3;

    message Clearing {
        string date = 1;
        Store store = 2;
        Company company = 3;
        repeated Product products = 4;
        message Store {
            uint64 id = 1;
            string image = 2;
            string address = 3;
        }
        message Company {
            uint64 id = 1;
            string name = 2;
        }
        message Product {
            uint64 id = 1;
            string name = 2;
            uint32 price = 3;
        }
    }
}
// gRPCのリクエスト

    /**
     * 購入履歴
     *
     * @param {any} token
     * @return 購入履歴
     */
    public historyRequest = (token: any) => {
        return new Promise(resolve => {
            var ret: any
            const req = new ClearingHistoryRequest()
            req.setToken(token)

            const client = new WebAppServiceClient("http://localhost:8080", {})
            client.clearingHistory(req, (err: any, res: any) => {
                if (err || res === null) {
                    throw err
                }

                // 購入履歴の取得
                const clearingHistories = res.getClearinghistoryList()

                // 購入商品の取得
                let products: any;
                for (let i = 0; i < clearingHistories.length; i++) {
                    products = clearingHistories[i].getProductsList()
                }

                // 返却値の生成
                let histories = new Array(clearingHistories.length)
                for (let i = 0; i < clearingHistories.length; i++) {
                    histories[i] = {
                        date: clearingHistories[i].getDate(),
                        store: {
                            id: clearingHistories[i].getStore().getId(),
                            image: clearingHistories[i].getStore().getImage(),
                            address: clearingHistories[i].getStore().getAddress()
                        },
                        company: {
                            id: clearingHistories[i].getCompany().getId(),
                            name: clearingHistories[i].getCompany().getName()
                        },
                        product: {
                            id: products[0].getId(),
                            name: products[0].getName(),
                            price: products[0].getPrice()
                        }
                    }
                }

                resolve(histories)
            })
        })
// 購入履歴
export interface iStore {
    id: number,
    image: string,
    address: string
}
export interface iCompany {
    id: number,
    name: string
}
export interface iProduct {
    id: number,
    name: string,
    price: number
}

export const getHistory = (token: any) => {
    return async (dispatch: Dispatch<Action>) => {
        try {
            dispatch({ type: actionTypes.START_REQUEST })

            const histories: any = await User.historyRequest(token)
            console.log(histories)
            dispatch(setHistory(histories))

            dispatch({ type: actionTypes.COMPLETE_REQUEST })
        } catch (e) {
            dispatch({ type: actionTypes.COMPLETE_REQUEST })
            dispatch(setNotification('error', 'エラーが発生しました!'))
        }
    }
}
export const setHistory = (histories: any) => ({
    type: actionTypes.SET_HISTORY,
    payload: {
        histories: histories
    }
})

// Reducer

import * as actionTypes from '../utils/actionTypes'
import * as actions from '../actions'

type Actions = (
    | ReturnType<typeof actions.setHistory>
)

interface iState {
    histories: [
        {
            date: string,
            store: actions.iStore,
            company: actions.iCompany,
            products: actions.iProduct[]
        }
    ]
}

const initialState: iState = {
    histories: [
        {
            date: "",
            store: {
                id: 0,
                image: "",
                address: ""
            },
            company: {
                id: 0,
                name: ""
            },
            products: [
                {
                    id: 0,
                    name: "",
                    price: 0
                }
            ]
        }
    ]
}

const HistoryReducer = (state: iState = initialState, action: Actions) => {
    switch (action.type) {
        case actionTypes.SET_HISTORY:
            Object.assign({}, action.payload.histories)
            console.log(state)
            return Object.assign({}, state, {
                state: action.payload.histories
            })
    }

    return state
}

export default HistoryReducer

追記

Reducerを下記の様に修正いたしました。

import * as actionTypes from '../utils/actionTypes'
import * as actions from '../actions'

type Actions = (
    | ReturnType<typeof actions.setHistory>
)

type History = {
    date: string,
    store: actions.iStore,
    company: actions.iCompany,
    products: actions.Product[]
}

interface iState {
    histories: History[]
}

const initialState: iState = {
    histories: []
}

const HistoryReducer = (state: iState = initialState, action: Actions) => {
    switch (action.type) {
        case actionTypes.SET_HISTORY:
            return Object.assign({}, state, {
                state: action.payload.histories
            })
    }

    return state
}

export default HistoryReducer

actionに記述していたinterface iProductも下記の様に修正いたしました。

// 購入履歴
export interface iStore {
    id: number,
    image: string,
    address: string
}
export interface iCompany {
    id: number,
    name: string
}
export type Product = {
    id: number,
    name: string,
    price: number
}

gRPCのレスポンスは以下の様に返ってきます。

(4) [{…}, {…}, {…}, {…}]
0:
date: "2020/01/29"
store: {id: 1, image: "", address: "滋賀県彦根市"}
company: {id: 1, name: "セブンイレブン"}
product:
id: 1
name: "コーラ"
price: 150
__proto__: Object
__proto__: Object
1: {date: "2020/01/29", store: {…}, company: {…}, product: {…}}
2: {date: "2020/01/29", store: {…}, company: {…}, product: {…}}
3: {date: "2020/01/29", store: {…}, company: {…}, product: {…}}
length: 4

上記には記述されていませんが、case actionTypes.SET_HISTORYでreturnする前に

Object.assign({}, state, {
     state: action.payload.histories
})
console.log(state)

をすると下記の様に表示されます。

{histories: Array(0)}
histories: Array(0)
length: 0
1

1 件の回答 1

0

Object.assign({}, state.histories, action.payload.histories)としたところうまく更新されました!ありがとうございました!

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。