Principiante Alerta! :) Estoy configurando el objeto FormData infantil en el componente y, a continuación, pasar a los padres de componente mediante formReducer y el envío, pero en los padres formData.entradas() siempre está vacío!
ChildComponent.js
function ChildComponent({signed, fileAttached}){
const { dispatch } = useContext(ContactFormContext);
const changeHandler = (event) => {
const formData = new FormData();
formData.append('File', event.target.files[0]);
dispatch({ type: "FILE_ATTACHED", payload: formData })
};
return (
<>
<div>
<input type="file" name="file" onChange={changeHandler} />
</div>
</>);
}
ParentComponent.js
function useFormProgress(fileAttached) {
function goForward() {
const currentStep = 1;
let appvariables = [
{
"key": "PUID",
"value": "a2sd"
},
{
"key": "ApplicationNames",
"value": "Trello, abc"
}
];
switch(currentStep) {
case 0:
break;
case 1:
console.log(fileAttached);
if(fileAttached != null)
sendEmail("Resignation Letter", appvariables, fileAttached);
break;
}
}
return [goForward];
}
function sendEmail(templateName, variables, attachment){
console.log("sending email...");
const requestBody = {
"templateName": templateName,
"recipients": [
"[email protected]"
],
"variables": variables,
"files": attachment
};
fetch('https://localhost:5001/api/Email',{
method:'Post',
body: JSON.stringify(requestBody),
headers:{'Content-Type': 'application/json'},
});
}
const initialState = {
signed: "",
fileAttached: null
};
function formReducer(state, action) {
switch (action.type) {
case "SIGNED":
return { ...state, signed: action.payload };
case "FILE_ATTACHED":
return {...state, fileAttached: action.payload};
default:
throw new Error();
}
}
function ParentComponent() {
const [state, dispatch] = useReducer(formReducer, initialState);
const { signed, fileAttached } = state;
const steps = [<ChildComponent {...{signed, fileAttached}}/>];
const [goForward] = useFormProgress(fileAttached);
return (
<ContactFormContext.Provider value={{ dispatch }}>
<div>{steps[0]}
<div><button onClick={e => {
e.preventDefault();
goForward();
}}
> Parent Button
</button>
</div>
</div>
</ContactFormContext.Provider>
);
}
ContactFormContext.js
const ContactFormContext = React.createContext();
En la instrucción switch de arriba (ParentComponent), el de la consola.log(FileAttached) muestra el objeto FormData con las entradas de 0(ver imagen adjunta), también la solicitud de la API no es correcta.!
puedes probarlo en https://jscomplete.com/playground
para añadir un contexto en la parte superior
agregar niño código de componente
agregar parentcomponent código
agregue la siguiente línea
ReactDOM.render(<ParentComponent/>, mountNode);
MyAPI Método
[HttpPost]
public JsonResult Get(EmailRequest email)
{
//the request never comes here
}
EmailRequest.cs
public class EmailRequest
{
public string TemplateName { get; set; }
public string[] Recipients { get; set; }
public List<Variables> Variables { get; set; }
public FormFileCollection files { get; set; }
}