私はreduxサンクを使用していますが、次の問題があります。 uploadClientImage
ディスパッチは、データベースへのイメージオブジェクトを作成し、イメージIDを返します。Redux Thunkがアクションをディスパッチしないで注文
私はclient_infoを作成する前に2つのイメージIDが必要です。
問題はclients
のアキソスポストが2 uploadClientImage
のディスパッチからIDを取得する前に呼び出されています。その2回のディスパッチがAxiosポストリクエストの前に完了するまで待つ方法はありますか?
export function uploadClientImage(image_file) {
return function(dispatch) {
var formData = new FormData();
for (var key in image_file) {
formData.append(key, image_file[key]);
}
console.log(formData);
axios.post(`${API_URL}/photos`, formData, {withCredentials: true, headers: {'Content-Type': 'multipart/form-data'}})
.then(response => {
var image_id = response.data.id;
return image_id;
})
.catch(() => {
console.log("Can't fileUpload");
});
}
}
export function createClient(client_info, logo, photo) {
return function(dispatch) {
var logo = client_info.logo_id[0];
var logo_id= dispatch(uploadClientImage(logo);
var photo = client_info.photo_id[0];
var photo_id = dispatch(uploadClientImage(photo));
client_info["photo_id"] = photo_id;
client_info["logo_id"] = logo_id;
axios.post(`${API_URL}/clients`, client_info, {withCredentials: true})
.then(response => {
//......
})
.catch(() => {
console.log("Can't create client");
});
}
}
おそらく 'uploadClientImage'は何か非同期を行います。その関数を投稿した場合は、具体的なアドバイスが得られるかもしれませんが、一般的には約束やコールバック関数が必要です。 (もしあなたがAxiosも使っているなら、あなたはすでに約束をしているかもしれません) – azium
@azium他の機能を追加しました。ありがとう! – lost9123193