Firebase React/Redux multipath updates from array

I have an array of objects that I need to push to firebase. Each object should have its own push key. The only way I have been able to accomplish this is by map over the array and passing each object to a redux action that handles the individual object push. I know this not the best way to do this and was wondering how else this can be accomplished?

When I try to pass the array to the action (to build an update object to pass to firebase.database().ref().update()) I get an error saying that it can only accept plain objects. Does the array need to be converted to an object.

const arr = [{0: "x", 1:"y"}, {0:"a", 1: "b"}]
this.props.action(arr)// throws error "Actions must be plain objects"

Is this not possible? Should I be using Promises instead?

I'm sure there is an answer to this but I can't find it so any direction would be greatly appreciated! Thanks!

Below are the screenshots for the firebase data and my array data

Firebase Data Array Data

Upvotes: 0

Views: 277

Answers (1)

Ok I figured it out.

//action (passed attendingMarkets array)
export const vendorTest = (vendorUid, attendingMarkets) => {
	var updates = {};

	attendingMarkets.map((map, idx) => {
		const date = map.date;
		const market = map.market;
		var newMarketKey = firebase
			.database()
			.ref()
			.child("/vendors/" + vendorUid + "/markets")
			.push().key;
		updates["/vendors/" + vendorUid + "/markets/" + newMarketKey] = {
			date,
			market
		};
	});
	return dispatch => {
		firebase
			.database()
			.ref()
			.update(updates)
			.then(() => {
				dispatch({ type: VENDOR_ADD_MARKETS });
			});
	};
};

Upvotes: 0

Related Questions